three.webgpu.js 1.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix2, Matrix3, Matrix4, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, InterleavedBufferAttribute, DynamicDrawUsage, NoColorSpace, UnsignedIntType, IntType, NearestFilter, Sphere, BackSide, Euler, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, SRGBColorSpace, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, OrthographicCamera, PerspectiveCamera, RenderTarget, CubeUVReflectionMapping, BufferGeometry, BufferAttribute, LinearSRGBColorSpace, RGBAFormat, HalfFloatType, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, arrayNeedsUint32, DoubleSide, Camera, DepthArrayTexture, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, RGFormat, BasicShadowMap, SphereGeometry, RenderTargetArray, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, 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, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<string>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns `true` if the current rendering produces motion vectors.
  121. *
  122. * @param {Renderer} renderer - The renderer.
  123. * @return {boolean} Whether the current rendering produces motion vectors or not.
  124. */
  125. needsVelocity( renderer ) {
  126. const mrt = renderer.getMRT();
  127. return ( mrt !== null && mrt.has( 'velocity' ) );
  128. }
  129. /**
  130. * Returns monitoring data for the given render object.
  131. *
  132. * @param {RenderObject} renderObject - The render object.
  133. * @return {Object} The monitoring data.
  134. */
  135. getRenderObjectData( renderObject ) {
  136. let data = this.renderObjects.get( renderObject );
  137. if ( data === undefined ) {
  138. const { geometry, material, object } = renderObject;
  139. data = {
  140. material: this.getMaterialData( material ),
  141. geometry: {
  142. id: geometry.id,
  143. attributes: this.getAttributesData( geometry.attributes ),
  144. indexVersion: geometry.index ? geometry.index.version : null,
  145. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  146. },
  147. worldMatrix: object.matrixWorld.clone()
  148. };
  149. if ( object.center ) {
  150. data.center = object.center.clone();
  151. }
  152. if ( object.morphTargetInfluences ) {
  153. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  154. }
  155. if ( renderObject.bundle !== null ) {
  156. data.version = renderObject.bundle.version;
  157. }
  158. if ( data.material.transmission > 0 ) {
  159. const { width, height } = renderObject.context;
  160. data.bufferWidth = width;
  161. data.bufferHeight = height;
  162. }
  163. this.renderObjects.set( renderObject, data );
  164. }
  165. return data;
  166. }
  167. /**
  168. * Returns an attribute data structure holding the attributes versions for
  169. * monitoring.
  170. *
  171. * @param {Object} attributes - The geometry attributes.
  172. * @return {Object} An object for monitoring the versions of attributes.
  173. */
  174. getAttributesData( attributes ) {
  175. const attributesData = {};
  176. for ( const name in attributes ) {
  177. const attribute = attributes[ name ];
  178. attributesData[ name ] = {
  179. version: attribute.version
  180. };
  181. }
  182. return attributesData;
  183. }
  184. /**
  185. * Returns `true` if the node builder's material uses
  186. * node properties.
  187. *
  188. * @param {NodeBuilder} builder - The current node builder.
  189. * @return {boolean} Whether the node builder's material uses node properties or not.
  190. */
  191. containsNode( builder ) {
  192. const material = builder.material;
  193. for ( const property in material ) {
  194. if ( material[ property ] && material[ property ].isNode )
  195. return true;
  196. }
  197. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  198. return true;
  199. return false;
  200. }
  201. /**
  202. * Returns a material data structure holding the material property values for
  203. * monitoring.
  204. *
  205. * @param {Material} material - The material.
  206. * @return {Object} An object for monitoring material properties.
  207. */
  208. getMaterialData( material ) {
  209. const data = {};
  210. for ( const property of this.refreshUniforms ) {
  211. const value = material[ property ];
  212. if ( value === null || value === undefined ) continue;
  213. if ( typeof value === 'object' && value.clone !== undefined ) {
  214. if ( value.isTexture === true ) {
  215. data[ property ] = { id: value.id, version: value.version };
  216. } else {
  217. data[ property ] = value.clone();
  218. }
  219. } else {
  220. data[ property ] = value;
  221. }
  222. }
  223. return data;
  224. }
  225. /**
  226. * Returns `true` if the given render object has not changed its state.
  227. *
  228. * @param {RenderObject} renderObject - The render object.
  229. * @return {boolean} Whether the given render object has changed its state or not.
  230. */
  231. equals( renderObject ) {
  232. const { object, material, geometry } = renderObject;
  233. const renderObjectData = this.getRenderObjectData( renderObject );
  234. // world matrix
  235. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  236. renderObjectData.worldMatrix.copy( object.matrixWorld );
  237. return false;
  238. }
  239. // material
  240. const materialData = renderObjectData.material;
  241. for ( const property in materialData ) {
  242. const value = materialData[ property ];
  243. const mtlValue = material[ property ];
  244. if ( value.equals !== undefined ) {
  245. if ( value.equals( mtlValue ) === false ) {
  246. value.copy( mtlValue );
  247. return false;
  248. }
  249. } else if ( mtlValue.isTexture === true ) {
  250. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  251. value.id = mtlValue.id;
  252. value.version = mtlValue.version;
  253. return false;
  254. }
  255. } else if ( value !== mtlValue ) {
  256. materialData[ property ] = mtlValue;
  257. return false;
  258. }
  259. }
  260. if ( materialData.transmission > 0 ) {
  261. const { width, height } = renderObject.context;
  262. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  263. renderObjectData.bufferWidth = width;
  264. renderObjectData.bufferHeight = height;
  265. return false;
  266. }
  267. }
  268. // geometry
  269. const storedGeometryData = renderObjectData.geometry;
  270. const attributes = geometry.attributes;
  271. const storedAttributes = storedGeometryData.attributes;
  272. const storedAttributeNames = Object.keys( storedAttributes );
  273. const currentAttributeNames = Object.keys( attributes );
  274. if ( storedGeometryData.id !== geometry.id ) {
  275. storedGeometryData.id = geometry.id;
  276. return false;
  277. }
  278. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  279. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  280. return false;
  281. }
  282. // compare each attribute
  283. for ( const name of storedAttributeNames ) {
  284. const storedAttributeData = storedAttributes[ name ];
  285. const attribute = attributes[ name ];
  286. if ( attribute === undefined ) {
  287. // attribute was removed
  288. delete storedAttributes[ name ];
  289. return false;
  290. }
  291. if ( storedAttributeData.version !== attribute.version ) {
  292. storedAttributeData.version = attribute.version;
  293. return false;
  294. }
  295. }
  296. // check index
  297. const index = geometry.index;
  298. const storedIndexVersion = storedGeometryData.indexVersion;
  299. const currentIndexVersion = index ? index.version : null;
  300. if ( storedIndexVersion !== currentIndexVersion ) {
  301. storedGeometryData.indexVersion = currentIndexVersion;
  302. return false;
  303. }
  304. // check drawRange
  305. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  306. storedGeometryData.drawRange.start = geometry.drawRange.start;
  307. storedGeometryData.drawRange.count = geometry.drawRange.count;
  308. return false;
  309. }
  310. // morph targets
  311. if ( renderObjectData.morphTargetInfluences ) {
  312. let morphChanged = false;
  313. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  314. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  315. morphChanged = true;
  316. }
  317. }
  318. if ( morphChanged ) return true;
  319. }
  320. // center
  321. if ( renderObjectData.center ) {
  322. if ( renderObjectData.center.equals( object.center ) === false ) {
  323. renderObjectData.center.copy( object.center );
  324. return true;
  325. }
  326. }
  327. // bundle
  328. if ( renderObject.bundle !== null ) {
  329. renderObjectData.version = renderObject.bundle.version;
  330. }
  331. return true;
  332. }
  333. /**
  334. * Checks if the given render object requires a refresh.
  335. *
  336. * @param {RenderObject} renderObject - The render object.
  337. * @param {NodeFrame} nodeFrame - The current node frame.
  338. * @return {boolean} Whether the given render object requires a refresh or not.
  339. */
  340. needsRefresh( renderObject, nodeFrame ) {
  341. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  342. return true;
  343. const { renderId } = nodeFrame;
  344. if ( this.renderId !== renderId ) {
  345. this.renderId = renderId;
  346. return true;
  347. }
  348. const isStatic = renderObject.object.static === true;
  349. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  350. if ( isStatic || isBundle )
  351. return false;
  352. const notEqual = this.equals( renderObject ) !== true;
  353. return notEqual;
  354. }
  355. }
  356. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  357. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  358. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  359. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  360. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  361. function cyrb53( value, seed = 0 ) {
  362. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  363. if ( value instanceof Array ) {
  364. for ( let i = 0, val; i < value.length; i ++ ) {
  365. val = value[ i ];
  366. h1 = Math.imul( h1 ^ val, 2654435761 );
  367. h2 = Math.imul( h2 ^ val, 1597334677 );
  368. }
  369. } else {
  370. for ( let i = 0, ch; i < value.length; i ++ ) {
  371. ch = value.charCodeAt( i );
  372. h1 = Math.imul( h1 ^ ch, 2654435761 );
  373. h2 = Math.imul( h2 ^ ch, 1597334677 );
  374. }
  375. }
  376. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  377. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  378. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  379. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  380. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  381. }
  382. /**
  383. * Computes a hash for the given string.
  384. *
  385. * @method
  386. * @param {string} str - The string to be hashed.
  387. * @return {number} The hash.
  388. */
  389. const hashString = ( str ) => cyrb53( str );
  390. /**
  391. * Computes a hash for the given array.
  392. *
  393. * @method
  394. * @param {Array<number>} array - The array to be hashed.
  395. * @return {number} The hash.
  396. */
  397. const hashArray = ( array ) => cyrb53( array );
  398. /**
  399. * Computes a hash for the given list of parameters.
  400. *
  401. * @method
  402. * @param {...number} params - A list of parameters.
  403. * @return {number} The hash.
  404. */
  405. const hash$1 = ( ...params ) => cyrb53( params );
  406. /**
  407. * Computes a cache key for the given node.
  408. *
  409. * @method
  410. * @param {Object|Node} object - The object to be hashed.
  411. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  412. * @return {number} The hash.
  413. */
  414. function getCacheKey$1( object, force = false ) {
  415. const values = [];
  416. if ( object.isNode === true ) {
  417. values.push( object.id );
  418. object = object.getSelf();
  419. }
  420. for ( const { property, childNode } of getNodeChildren( object ) ) {
  421. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  422. }
  423. return cyrb53( values );
  424. }
  425. /**
  426. * This generator function can be used to iterate over the node children
  427. * of the given object.
  428. *
  429. * @generator
  430. * @param {Object} node - The object to be hashed.
  431. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  432. * @yields {Object} A result node holding the property, index (if available) and the child node.
  433. */
  434. function* getNodeChildren( node, toJSON = false ) {
  435. for ( const property in node ) {
  436. // Ignore private properties.
  437. if ( property.startsWith( '_' ) === true ) continue;
  438. const object = node[ property ];
  439. if ( Array.isArray( object ) === true ) {
  440. for ( let i = 0; i < object.length; i ++ ) {
  441. const child = object[ i ];
  442. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  443. yield { property, index: i, childNode: child };
  444. }
  445. }
  446. } else if ( object && object.isNode === true ) {
  447. yield { property, childNode: object };
  448. } else if ( typeof object === 'object' ) {
  449. for ( const subProperty in object ) {
  450. const child = object[ subProperty ];
  451. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  452. yield { property, index: subProperty, childNode: child };
  453. }
  454. }
  455. }
  456. }
  457. }
  458. const typeFromLength = /*@__PURE__*/ new Map( [
  459. [ 1, 'float' ],
  460. [ 2, 'vec2' ],
  461. [ 3, 'vec3' ],
  462. [ 4, 'vec4' ],
  463. [ 9, 'mat3' ],
  464. [ 16, 'mat4' ]
  465. ] );
  466. const dataFromObject = /*@__PURE__*/ new WeakMap();
  467. /**
  468. * Returns the data type for the given the length.
  469. *
  470. * @method
  471. * @param {number} length - The length.
  472. * @return {string} The data type.
  473. */
  474. function getTypeFromLength( length ) {
  475. return typeFromLength.get( length );
  476. }
  477. /**
  478. * Returns the typed array for the given data type.
  479. *
  480. * @method
  481. * @param {string} type - The data type.
  482. * @return {TypedArray} The typed array.
  483. */
  484. function getTypedArrayFromType( type ) {
  485. // Handle component type for vectors and matrices
  486. if ( /[iu]?vec\d/.test( type ) ) {
  487. // Handle int vectors
  488. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  489. // Handle uint vectors
  490. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  491. // Default to float vectors
  492. return Float32Array;
  493. }
  494. // Handle matrices (always float)
  495. if ( /mat\d/.test( type ) ) return Float32Array;
  496. // Basic types
  497. if ( /float/.test( type ) ) return Float32Array;
  498. if ( /uint/.test( type ) ) return Uint32Array;
  499. if ( /int/.test( type ) ) return Int32Array;
  500. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  501. }
  502. /**
  503. * Returns the length for the given data type.
  504. *
  505. * @method
  506. * @param {string} type - The data type.
  507. * @return {number} The length.
  508. */
  509. function getLengthFromType( type ) {
  510. if ( /float|int|uint/.test( type ) ) return 1;
  511. if ( /vec2/.test( type ) ) return 2;
  512. if ( /vec3/.test( type ) ) return 3;
  513. if ( /vec4/.test( type ) ) return 4;
  514. if ( /mat2/.test( type ) ) return 4;
  515. if ( /mat3/.test( type ) ) return 9;
  516. if ( /mat4/.test( type ) ) return 16;
  517. console.error( 'THREE.TSL: Unsupported type:', type );
  518. }
  519. /**
  520. * Returns the data type for the given value.
  521. *
  522. * @method
  523. * @param {any} value - The value.
  524. * @return {?string} The data type.
  525. */
  526. function getValueType( value ) {
  527. if ( value === undefined || value === null ) return null;
  528. const typeOf = typeof value;
  529. if ( value.isNode === true ) {
  530. return 'node';
  531. } else if ( typeOf === 'number' ) {
  532. return 'float';
  533. } else if ( typeOf === 'boolean' ) {
  534. return 'bool';
  535. } else if ( typeOf === 'string' ) {
  536. return 'string';
  537. } else if ( typeOf === 'function' ) {
  538. return 'shader';
  539. } else if ( value.isVector2 === true ) {
  540. return 'vec2';
  541. } else if ( value.isVector3 === true ) {
  542. return 'vec3';
  543. } else if ( value.isVector4 === true ) {
  544. return 'vec4';
  545. } else if ( value.isMatrix2 === true ) {
  546. return 'mat2';
  547. } else if ( value.isMatrix3 === true ) {
  548. return 'mat3';
  549. } else if ( value.isMatrix4 === true ) {
  550. return 'mat4';
  551. } else if ( value.isColor === true ) {
  552. return 'color';
  553. } else if ( value instanceof ArrayBuffer ) {
  554. return 'ArrayBuffer';
  555. }
  556. return null;
  557. }
  558. /**
  559. * Returns the value/object for the given data type and parameters.
  560. *
  561. * @method
  562. * @param {string} type - The given type.
  563. * @param {...any} params - A parameter list.
  564. * @return {any} The value/object.
  565. */
  566. function getValueFromType( type, ...params ) {
  567. const last4 = type ? type.slice( -4 ) : undefined;
  568. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  569. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  570. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  571. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  572. }
  573. if ( type === 'color' ) {
  574. return new Color( ...params );
  575. } else if ( last4 === 'vec2' ) {
  576. return new Vector2( ...params );
  577. } else if ( last4 === 'vec3' ) {
  578. return new Vector3( ...params );
  579. } else if ( last4 === 'vec4' ) {
  580. return new Vector4( ...params );
  581. } else if ( last4 === 'mat2' ) {
  582. return new Matrix2( ...params );
  583. } else if ( last4 === 'mat3' ) {
  584. return new Matrix3( ...params );
  585. } else if ( last4 === 'mat4' ) {
  586. return new Matrix4( ...params );
  587. } else if ( type === 'bool' ) {
  588. return params[ 0 ] || false;
  589. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  590. return params[ 0 ] || 0;
  591. } else if ( type === 'string' ) {
  592. return params[ 0 ] || '';
  593. } else if ( type === 'ArrayBuffer' ) {
  594. return base64ToArrayBuffer( params[ 0 ] );
  595. }
  596. return null;
  597. }
  598. /**
  599. * Gets the object data that can be shared between different rendering steps.
  600. *
  601. * @param {Object} object - The object to get the data for.
  602. * @return {Object} The object data.
  603. */
  604. function getDataFromObject( object ) {
  605. let data = dataFromObject.get( object );
  606. if ( data === undefined ) {
  607. data = {};
  608. dataFromObject.set( object, data );
  609. }
  610. return data;
  611. }
  612. /**
  613. * Converts the given array buffer to a Base64 string.
  614. *
  615. * @method
  616. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  617. * @return {string} The Base64 string.
  618. */
  619. function arrayBufferToBase64( arrayBuffer ) {
  620. let chars = '';
  621. const array = new Uint8Array( arrayBuffer );
  622. for ( let i = 0; i < array.length; i ++ ) {
  623. chars += String.fromCharCode( array[ i ] );
  624. }
  625. return btoa( chars );
  626. }
  627. /**
  628. * Converts the given Base64 string to an array buffer.
  629. *
  630. * @method
  631. * @param {string} base64 - The Base64 string.
  632. * @return {ArrayBuffer} The array buffer.
  633. */
  634. function base64ToArrayBuffer( base64 ) {
  635. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  636. }
  637. var NodeUtils = /*#__PURE__*/Object.freeze({
  638. __proto__: null,
  639. arrayBufferToBase64: arrayBufferToBase64,
  640. base64ToArrayBuffer: base64ToArrayBuffer,
  641. getCacheKey: getCacheKey$1,
  642. getDataFromObject: getDataFromObject,
  643. getLengthFromType: getLengthFromType,
  644. getNodeChildren: getNodeChildren,
  645. getTypeFromLength: getTypeFromLength,
  646. getTypedArrayFromType: getTypedArrayFromType,
  647. getValueFromType: getValueFromType,
  648. getValueType: getValueType,
  649. hash: hash$1,
  650. hashArray: hashArray,
  651. hashString: hashString
  652. });
  653. /**
  654. * Possible shader stages.
  655. *
  656. * @property {string} VERTEX The vertex shader stage.
  657. * @property {string} FRAGMENT The fragment shader stage.
  658. */
  659. const NodeShaderStage = {
  660. VERTEX: 'vertex',
  661. FRAGMENT: 'fragment'
  662. };
  663. /**
  664. * Update types of a node.
  665. *
  666. * @property {string} NONE The update method is not executed.
  667. * @property {string} FRAME The update method is executed per frame.
  668. * @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.
  669. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  670. */
  671. const NodeUpdateType = {
  672. NONE: 'none',
  673. FRAME: 'frame',
  674. RENDER: 'render',
  675. OBJECT: 'object'
  676. };
  677. /**
  678. * Data types of a node.
  679. *
  680. * @property {string} BOOLEAN Boolean type.
  681. * @property {string} INTEGER Integer type.
  682. * @property {string} FLOAT Float type.
  683. * @property {string} VECTOR2 Two-dimensional vector type.
  684. * @property {string} VECTOR3 Three-dimensional vector type.
  685. * @property {string} VECTOR4 Four-dimensional vector type.
  686. * @property {string} MATRIX2 2x2 matrix type.
  687. * @property {string} MATRIX3 3x3 matrix type.
  688. * @property {string} MATRIX4 4x4 matrix type.
  689. */
  690. const NodeType = {
  691. BOOLEAN: 'bool',
  692. INTEGER: 'int',
  693. FLOAT: 'float',
  694. VECTOR2: 'vec2',
  695. VECTOR3: 'vec3',
  696. VECTOR4: 'vec4',
  697. MATRIX2: 'mat2',
  698. MATRIX3: 'mat3',
  699. MATRIX4: 'mat4'
  700. };
  701. /**
  702. * Access types of a node. These are relevant for compute and storage usage.
  703. *
  704. * @property {string} READ_ONLY Read-only access
  705. * @property {string} WRITE_ONLY Write-only access.
  706. * @property {string} READ_WRITE Read and write access.
  707. */
  708. const NodeAccess = {
  709. READ_ONLY: 'readOnly',
  710. WRITE_ONLY: 'writeOnly',
  711. READ_WRITE: 'readWrite',
  712. };
  713. const defaultShaderStages = [ 'fragment', 'vertex' ];
  714. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  715. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  716. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  717. let _nodeId = 0;
  718. /**
  719. * Base class for all nodes.
  720. *
  721. * @augments EventDispatcher
  722. */
  723. class Node extends EventDispatcher {
  724. static get type() {
  725. return 'Node';
  726. }
  727. /**
  728. * Constructs a new node.
  729. *
  730. * @param {?string} nodeType - The node type.
  731. */
  732. constructor( nodeType = null ) {
  733. super();
  734. /**
  735. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  736. *
  737. * @type {?string}
  738. * @default null
  739. */
  740. this.nodeType = nodeType;
  741. /**
  742. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  743. *
  744. * @type {string}
  745. * @default 'none'
  746. */
  747. this.updateType = NodeUpdateType.NONE;
  748. /**
  749. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  750. *
  751. * @type {string}
  752. * @default 'none'
  753. */
  754. this.updateBeforeType = NodeUpdateType.NONE;
  755. /**
  756. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  757. *
  758. * @type {string}
  759. * @default 'none'
  760. */
  761. this.updateAfterType = NodeUpdateType.NONE;
  762. /**
  763. * The UUID of the node.
  764. *
  765. * @type {string}
  766. * @readonly
  767. */
  768. this.uuid = MathUtils.generateUUID();
  769. /**
  770. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  771. *
  772. * @type {number}
  773. * @readonly
  774. * @default 0
  775. */
  776. this.version = 0;
  777. /**
  778. * Whether this node is global or not. This property is relevant for the internal
  779. * node caching system. All nodes which should be declared just once should
  780. * set this flag to `true` (a typical example is {@link AttributeNode}).
  781. *
  782. * @type {boolean}
  783. * @default false
  784. */
  785. this.global = false;
  786. /**
  787. * Create a list of parents for this node during the build process.
  788. *
  789. * @type {boolean}
  790. * @default false
  791. */
  792. this.parents = false;
  793. /**
  794. * This flag can be used for type testing.
  795. *
  796. * @type {boolean}
  797. * @readonly
  798. * @default true
  799. */
  800. this.isNode = true;
  801. // private
  802. /**
  803. * The cache key of this node.
  804. *
  805. * @private
  806. * @type {?number}
  807. * @default null
  808. */
  809. this._cacheKey = null;
  810. /**
  811. * The cache key 's version.
  812. *
  813. * @private
  814. * @type {number}
  815. * @default 0
  816. */
  817. this._cacheKeyVersion = 0;
  818. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  819. }
  820. /**
  821. * Set this property to `true` when the node should be regenerated.
  822. *
  823. * @type {boolean}
  824. * @default false
  825. * @param {boolean} value
  826. */
  827. set needsUpdate( value ) {
  828. if ( value === true ) {
  829. this.version ++;
  830. }
  831. }
  832. /**
  833. * The type of the class. The value is usually the constructor name.
  834. *
  835. * @type {string}
  836. * @readonly
  837. */
  838. get type() {
  839. return this.constructor.type;
  840. }
  841. /**
  842. * Convenient method for defining {@link Node#update}.
  843. *
  844. * @param {Function} callback - The update method.
  845. * @param {string} updateType - The update type.
  846. * @return {Node} A reference to this node.
  847. */
  848. onUpdate( callback, updateType ) {
  849. this.updateType = updateType;
  850. this.update = callback.bind( this.getSelf() );
  851. return this;
  852. }
  853. /**
  854. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  855. * this method automatically sets the update type to `FRAME`.
  856. *
  857. * @param {Function} callback - The update method.
  858. * @return {Node} A reference to this node.
  859. */
  860. onFrameUpdate( callback ) {
  861. return this.onUpdate( callback, NodeUpdateType.FRAME );
  862. }
  863. /**
  864. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  865. * this method automatically sets the update type to `RENDER`.
  866. *
  867. * @param {Function} callback - The update method.
  868. * @return {Node} A reference to this node.
  869. */
  870. onRenderUpdate( callback ) {
  871. return this.onUpdate( callback, NodeUpdateType.RENDER );
  872. }
  873. /**
  874. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  875. * this method automatically sets the update type to `OBJECT`.
  876. *
  877. * @param {Function} callback - The update method.
  878. * @return {Node} A reference to this node.
  879. */
  880. onObjectUpdate( callback ) {
  881. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  882. }
  883. /**
  884. * Convenient method for defining {@link Node#updateReference}.
  885. *
  886. * @param {Function} callback - The update method.
  887. * @return {Node} A reference to this node.
  888. */
  889. onReference( callback ) {
  890. this.updateReference = callback.bind( this.getSelf() );
  891. return this;
  892. }
  893. /**
  894. * The `this` reference might point to a Proxy so this method can be used
  895. * to get the reference to the actual node instance.
  896. *
  897. * @return {Node} A reference to the node.
  898. */
  899. getSelf() {
  900. // Returns non-node object.
  901. return this.self || this;
  902. }
  903. /**
  904. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  905. * to such objects based on a given state (e.g. the current node frame or builder).
  906. *
  907. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  908. * @return {any} The updated reference.
  909. */
  910. updateReference( /*state*/ ) {
  911. return this;
  912. }
  913. /**
  914. * By default this method returns the value of the {@link Node#global} flag. This method
  915. * can be overwritten in derived classes if an analytical way is required to determine the
  916. * global status.
  917. *
  918. * @param {NodeBuilder} builder - The current node builder.
  919. * @return {boolean} Whether this node is global or not.
  920. */
  921. isGlobal( /*builder*/ ) {
  922. return this.global;
  923. }
  924. /**
  925. * Generator function that can be used to iterate over the child nodes.
  926. *
  927. * @generator
  928. * @yields {Node} A child node.
  929. */
  930. * getChildren() {
  931. for ( const { childNode } of getNodeChildren( this ) ) {
  932. yield childNode;
  933. }
  934. }
  935. /**
  936. * Calling this method dispatches the `dispose` event. This event can be used
  937. * to register event listeners for clean up tasks.
  938. */
  939. dispose() {
  940. this.dispatchEvent( { type: 'dispose' } );
  941. }
  942. /**
  943. * Callback for {@link Node#traverse}.
  944. *
  945. * @callback traverseCallback
  946. * @param {Node} node - The current node.
  947. */
  948. /**
  949. * Can be used to traverse through the node's hierarchy.
  950. *
  951. * @param {traverseCallback} callback - A callback that is executed per node.
  952. */
  953. traverse( callback ) {
  954. callback( this );
  955. for ( const childNode of this.getChildren() ) {
  956. childNode.traverse( callback );
  957. }
  958. }
  959. /**
  960. * Returns the cache key for this node.
  961. *
  962. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  963. * @return {number} The cache key of the node.
  964. */
  965. getCacheKey( force = false ) {
  966. force = force || this.version !== this._cacheKeyVersion;
  967. if ( force === true || this._cacheKey === null ) {
  968. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  969. this._cacheKeyVersion = this.version;
  970. }
  971. return this._cacheKey;
  972. }
  973. /**
  974. * Generate a custom cache key for this node.
  975. *
  976. * @return {number} The cache key of the node.
  977. */
  978. customCacheKey() {
  979. return 0;
  980. }
  981. /**
  982. * Returns the references to this node which is by default `this`.
  983. *
  984. * @return {Node} A reference to this node.
  985. */
  986. getScope() {
  987. return this;
  988. }
  989. /**
  990. * Returns the hash of the node which is used to identify the node. By default it's
  991. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  992. * depending on their implementation.
  993. *
  994. * @param {NodeBuilder} builder - The current node builder.
  995. * @return {string} The hash.
  996. */
  997. getHash( /*builder*/ ) {
  998. return this.uuid;
  999. }
  1000. /**
  1001. * Returns the update type of {@link Node#update}.
  1002. *
  1003. * @return {NodeUpdateType} The update type.
  1004. */
  1005. getUpdateType() {
  1006. return this.updateType;
  1007. }
  1008. /**
  1009. * Returns the update type of {@link Node#updateBefore}.
  1010. *
  1011. * @return {NodeUpdateType} The update type.
  1012. */
  1013. getUpdateBeforeType() {
  1014. return this.updateBeforeType;
  1015. }
  1016. /**
  1017. * Returns the update type of {@link Node#updateAfter}.
  1018. *
  1019. * @return {NodeUpdateType} The update type.
  1020. */
  1021. getUpdateAfterType() {
  1022. return this.updateAfterType;
  1023. }
  1024. /**
  1025. * Certain types are composed of multiple elements. For example a `vec3`
  1026. * is composed of three `float` values. This method returns the type of
  1027. * these elements.
  1028. *
  1029. * @param {NodeBuilder} builder - The current node builder.
  1030. * @return {string} The type of the node.
  1031. */
  1032. getElementType( builder ) {
  1033. const type = this.getNodeType( builder );
  1034. const elementType = builder.getElementType( type );
  1035. return elementType;
  1036. }
  1037. /**
  1038. * Returns the node member type for the given name.
  1039. *
  1040. * @param {NodeBuilder} builder - The current node builder.
  1041. * @param {string} name - The name of the member.
  1042. * @return {string} The type of the node.
  1043. */
  1044. getMemberType( /*builder, name*/ ) {
  1045. return 'void';
  1046. }
  1047. /**
  1048. * Returns the node's type.
  1049. *
  1050. * @param {NodeBuilder} builder - The current node builder.
  1051. * @return {string} The type of the node.
  1052. */
  1053. getNodeType( builder ) {
  1054. const nodeProperties = builder.getNodeProperties( this );
  1055. if ( nodeProperties.outputNode ) {
  1056. return nodeProperties.outputNode.getNodeType( builder );
  1057. }
  1058. return this.nodeType;
  1059. }
  1060. /**
  1061. * This method is used during the build process of a node and ensures
  1062. * equal nodes are not built multiple times but just once. For example if
  1063. * `attribute( 'uv' )` is used multiple times by the user, the build
  1064. * process makes sure to process just the first node.
  1065. *
  1066. * @param {NodeBuilder} builder - The current node builder.
  1067. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1068. */
  1069. getShared( builder ) {
  1070. const hash = this.getHash( builder );
  1071. const nodeFromHash = builder.getNodeFromHash( hash );
  1072. return nodeFromHash || this;
  1073. }
  1074. /**
  1075. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1076. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1077. * The output node must be returned in the `return` statement.
  1078. *
  1079. * @param {NodeBuilder} builder - The current node builder.
  1080. * @return {?Node} The output node.
  1081. */
  1082. setup( builder ) {
  1083. const nodeProperties = builder.getNodeProperties( this );
  1084. let index = 0;
  1085. for ( const childNode of this.getChildren() ) {
  1086. nodeProperties[ 'node' + index ++ ] = childNode;
  1087. }
  1088. // return a outputNode if exists or null
  1089. return nodeProperties.outputNode || null;
  1090. }
  1091. /**
  1092. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1093. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1094. *
  1095. * @param {NodeBuilder} builder - The current node builder.
  1096. */
  1097. analyze( builder ) {
  1098. const usageCount = builder.increaseUsage( this );
  1099. if ( usageCount === 1 ) {
  1100. // node flow children
  1101. const nodeProperties = builder.getNodeProperties( this );
  1102. for ( const childNode of Object.values( nodeProperties ) ) {
  1103. if ( childNode && childNode.isNode === true ) {
  1104. childNode.build( builder );
  1105. }
  1106. }
  1107. }
  1108. }
  1109. /**
  1110. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1111. * This state builds the output node and returns the resulting shader string.
  1112. *
  1113. * @param {NodeBuilder} builder - The current node builder.
  1114. * @param {?string} output - Can be used to define the output type.
  1115. * @return {?string} The generated shader string.
  1116. */
  1117. generate( builder, output ) {
  1118. const { outputNode } = builder.getNodeProperties( this );
  1119. if ( outputNode && outputNode.isNode === true ) {
  1120. return outputNode.build( builder, output );
  1121. }
  1122. }
  1123. /**
  1124. * The method can be implemented to update the node's internal state before it is used to render an object.
  1125. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1126. *
  1127. * @abstract
  1128. * @param {NodeFrame} frame - A reference to the current node frame.
  1129. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1130. */
  1131. updateBefore( /*frame*/ ) {
  1132. console.warn( 'Abstract function.' );
  1133. }
  1134. /**
  1135. * The method can be implemented to update the node's internal state after it was used to render an object.
  1136. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1137. *
  1138. * @abstract
  1139. * @param {NodeFrame} frame - A reference to the current node frame.
  1140. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1141. */
  1142. updateAfter( /*frame*/ ) {
  1143. console.warn( 'Abstract function.' );
  1144. }
  1145. /**
  1146. * The method can be implemented to update the node's internal state when it is used to render an object.
  1147. * The {@link Node#updateType} property defines how often the update is executed.
  1148. *
  1149. * @abstract
  1150. * @param {NodeFrame} frame - A reference to the current node frame.
  1151. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1152. */
  1153. update( /*frame*/ ) {
  1154. console.warn( 'Abstract function.' );
  1155. }
  1156. /**
  1157. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1158. * - **setup**: Prepares the node and its children for the build process. This process can also create new nodes. Returns the node itself or a variant.
  1159. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1160. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1161. *
  1162. * @param {NodeBuilder} builder - The current node builder.
  1163. * @param {?string} [output=null] - Can be used to define the output type.
  1164. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1165. */
  1166. build( builder, output = null ) {
  1167. const refNode = this.getShared( builder );
  1168. if ( this !== refNode ) {
  1169. return refNode.build( builder, output );
  1170. }
  1171. builder.addNode( this );
  1172. builder.addChain( this );
  1173. /* Build stages expected results:
  1174. - "setup" -> Node
  1175. - "analyze" -> null
  1176. - "generate" -> String
  1177. */
  1178. let result = null;
  1179. const buildStage = builder.getBuildStage();
  1180. if ( buildStage === 'setup' ) {
  1181. this.updateReference( builder );
  1182. const properties = builder.getNodeProperties( this );
  1183. if ( properties.initialized !== true ) {
  1184. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1185. properties.initialized = true;
  1186. const outputNode = this.setup( builder ); // return a node or null
  1187. const isNodeOutput = outputNode && outputNode.isNode === true;
  1188. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1189. // !! no outputNode !!
  1190. //outputNode = builder.stack;
  1191. }*/
  1192. for ( const childNode of Object.values( properties ) ) {
  1193. if ( childNode && childNode.isNode === true ) {
  1194. if ( childNode.parents === true ) {
  1195. const childProperties = builder.getNodeProperties( childNode );
  1196. childProperties.parents = childProperties.parents || [];
  1197. childProperties.parents.push( this );
  1198. }
  1199. childNode.build( builder );
  1200. }
  1201. }
  1202. if ( isNodeOutput ) {
  1203. outputNode.build( builder );
  1204. }
  1205. properties.outputNode = outputNode;
  1206. }
  1207. result = properties.outputNode || null;
  1208. } else if ( buildStage === 'analyze' ) {
  1209. this.analyze( builder );
  1210. } else if ( buildStage === 'generate' ) {
  1211. const isGenerateOnce = this.generate.length === 1;
  1212. if ( isGenerateOnce ) {
  1213. const type = this.getNodeType( builder );
  1214. const nodeData = builder.getDataFromNode( this );
  1215. result = nodeData.snippet;
  1216. if ( result === undefined ) {
  1217. if ( nodeData.generated === undefined ) {
  1218. nodeData.generated = true;
  1219. result = this.generate( builder ) || '';
  1220. nodeData.snippet = result;
  1221. } else {
  1222. console.warn( 'THREE.Node: Recursion detected.', this );
  1223. result = '';
  1224. }
  1225. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1226. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1227. }
  1228. result = builder.format( result, type, output );
  1229. } else {
  1230. result = this.generate( builder, output ) || '';
  1231. }
  1232. }
  1233. builder.removeChain( this );
  1234. builder.addSequentialNode( this );
  1235. return result;
  1236. }
  1237. /**
  1238. * Returns the child nodes as a JSON object.
  1239. *
  1240. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1241. */
  1242. getSerializeChildren() {
  1243. return getNodeChildren( this );
  1244. }
  1245. /**
  1246. * Serializes the node to JSON.
  1247. *
  1248. * @param {Object} json - The output JSON object.
  1249. */
  1250. serialize( json ) {
  1251. const nodeChildren = this.getSerializeChildren();
  1252. const inputNodes = {};
  1253. for ( const { property, index, childNode } of nodeChildren ) {
  1254. if ( index !== undefined ) {
  1255. if ( inputNodes[ property ] === undefined ) {
  1256. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1257. }
  1258. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1259. } else {
  1260. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1261. }
  1262. }
  1263. if ( Object.keys( inputNodes ).length > 0 ) {
  1264. json.inputNodes = inputNodes;
  1265. }
  1266. }
  1267. /**
  1268. * Deserializes the node from the given JSON.
  1269. *
  1270. * @param {Object} json - The JSON object.
  1271. */
  1272. deserialize( json ) {
  1273. if ( json.inputNodes !== undefined ) {
  1274. const nodes = json.meta.nodes;
  1275. for ( const property in json.inputNodes ) {
  1276. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1277. const inputArray = [];
  1278. for ( const uuid of json.inputNodes[ property ] ) {
  1279. inputArray.push( nodes[ uuid ] );
  1280. }
  1281. this[ property ] = inputArray;
  1282. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1283. const inputObject = {};
  1284. for ( const subProperty in json.inputNodes[ property ] ) {
  1285. const uuid = json.inputNodes[ property ][ subProperty ];
  1286. inputObject[ subProperty ] = nodes[ uuid ];
  1287. }
  1288. this[ property ] = inputObject;
  1289. } else {
  1290. const uuid = json.inputNodes[ property ];
  1291. this[ property ] = nodes[ uuid ];
  1292. }
  1293. }
  1294. }
  1295. }
  1296. /**
  1297. * Serializes the node into the three.js JSON Object/Scene format.
  1298. *
  1299. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1300. * @return {Object} The serialized node.
  1301. */
  1302. toJSON( meta ) {
  1303. const { uuid, type } = this;
  1304. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1305. if ( isRoot ) {
  1306. meta = {
  1307. textures: {},
  1308. images: {},
  1309. nodes: {}
  1310. };
  1311. }
  1312. // serialize
  1313. let data = meta.nodes[ uuid ];
  1314. if ( data === undefined ) {
  1315. data = {
  1316. uuid,
  1317. type,
  1318. meta,
  1319. metadata: {
  1320. version: 4.6,
  1321. type: 'Node',
  1322. generator: 'Node.toJSON'
  1323. }
  1324. };
  1325. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1326. this.serialize( data );
  1327. delete data.meta;
  1328. }
  1329. // TODO: Copied from Object3D.toJSON
  1330. function extractFromCache( cache ) {
  1331. const values = [];
  1332. for ( const key in cache ) {
  1333. const data = cache[ key ];
  1334. delete data.metadata;
  1335. values.push( data );
  1336. }
  1337. return values;
  1338. }
  1339. if ( isRoot ) {
  1340. const textures = extractFromCache( meta.textures );
  1341. const images = extractFromCache( meta.images );
  1342. const nodes = extractFromCache( meta.nodes );
  1343. if ( textures.length > 0 ) data.textures = textures;
  1344. if ( images.length > 0 ) data.images = images;
  1345. if ( nodes.length > 0 ) data.nodes = nodes;
  1346. }
  1347. return data;
  1348. }
  1349. }
  1350. /**
  1351. * Base class for representing element access on an array-like
  1352. * node data structures.
  1353. *
  1354. * @augments Node
  1355. */
  1356. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1357. static get type() {
  1358. return 'ArrayElementNode';
  1359. }
  1360. /**
  1361. * Constructs an array element node.
  1362. *
  1363. * @param {Node} node - The array-like node.
  1364. * @param {Node} indexNode - The index node that defines the element access.
  1365. */
  1366. constructor( node, indexNode ) {
  1367. super();
  1368. /**
  1369. * The array-like node.
  1370. *
  1371. * @type {Node}
  1372. */
  1373. this.node = node;
  1374. /**
  1375. * The index node that defines the element access.
  1376. *
  1377. * @type {Node}
  1378. */
  1379. this.indexNode = indexNode;
  1380. /**
  1381. * This flag can be used for type testing.
  1382. *
  1383. * @type {boolean}
  1384. * @readonly
  1385. * @default true
  1386. */
  1387. this.isArrayElementNode = true;
  1388. }
  1389. /**
  1390. * This method is overwritten since the node type is inferred from the array-like node.
  1391. *
  1392. * @param {NodeBuilder} builder - The current node builder.
  1393. * @return {string} The node type.
  1394. */
  1395. getNodeType( builder ) {
  1396. return this.node.getElementType( builder );
  1397. }
  1398. generate( builder ) {
  1399. const indexType = this.indexNode.getNodeType( builder );
  1400. const nodeSnippet = this.node.build( builder );
  1401. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1402. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1403. }
  1404. }
  1405. /**
  1406. * This module is part of the TSL core and usually not used in app level code.
  1407. * It represents a convert operation during the shader generation process
  1408. * meaning it converts the data type of a node to a target data type.
  1409. *
  1410. * @augments Node
  1411. */
  1412. class ConvertNode extends Node {
  1413. static get type() {
  1414. return 'ConvertNode';
  1415. }
  1416. /**
  1417. * Constructs a new convert node.
  1418. *
  1419. * @param {Node} node - The node which type should be converted.
  1420. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1421. */
  1422. constructor( node, convertTo ) {
  1423. super();
  1424. /**
  1425. * The node which type should be converted.
  1426. *
  1427. * @type {Node}
  1428. */
  1429. this.node = node;
  1430. /**
  1431. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1432. *
  1433. * @type {string}
  1434. */
  1435. this.convertTo = convertTo;
  1436. }
  1437. /**
  1438. * This method is overwritten since the implementation tries to infer the best
  1439. * matching type from the {@link ConvertNode#convertTo} property.
  1440. *
  1441. * @param {NodeBuilder} builder - The current node builder.
  1442. * @return {string} The node type.
  1443. */
  1444. getNodeType( builder ) {
  1445. const requestType = this.node.getNodeType( builder );
  1446. let convertTo = null;
  1447. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1448. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1449. convertTo = overloadingType;
  1450. }
  1451. }
  1452. return convertTo;
  1453. }
  1454. serialize( data ) {
  1455. super.serialize( data );
  1456. data.convertTo = this.convertTo;
  1457. }
  1458. deserialize( data ) {
  1459. super.deserialize( data );
  1460. this.convertTo = data.convertTo;
  1461. }
  1462. generate( builder, output ) {
  1463. const node = this.node;
  1464. const type = this.getNodeType( builder );
  1465. const snippet = node.build( builder, type );
  1466. return builder.format( snippet, type, output );
  1467. }
  1468. }
  1469. /**
  1470. * This module uses cache management to create temporary variables
  1471. * if the node is used more than once to prevent duplicate calculations.
  1472. *
  1473. * The class acts as a base class for many other nodes types.
  1474. *
  1475. * @augments Node
  1476. */
  1477. class TempNode extends Node {
  1478. static get type() {
  1479. return 'TempNode';
  1480. }
  1481. /**
  1482. * Constructs a temp node.
  1483. *
  1484. * @param {?string} nodeType - The node type.
  1485. */
  1486. constructor( nodeType = null ) {
  1487. super( nodeType );
  1488. /**
  1489. * This flag can be used for type testing.
  1490. *
  1491. * @type {boolean}
  1492. * @readonly
  1493. * @default true
  1494. */
  1495. this.isTempNode = true;
  1496. }
  1497. /**
  1498. * Whether this node is used more than once in context of other nodes.
  1499. *
  1500. * @param {NodeBuilder} builder - The node builder.
  1501. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1502. */
  1503. hasDependencies( builder ) {
  1504. return builder.getDataFromNode( this ).usageCount > 1;
  1505. }
  1506. build( builder, output ) {
  1507. const buildStage = builder.getBuildStage();
  1508. if ( buildStage === 'generate' ) {
  1509. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1510. const nodeData = builder.getDataFromNode( this );
  1511. if ( nodeData.propertyName !== undefined ) {
  1512. return builder.format( nodeData.propertyName, type, output );
  1513. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1514. const snippet = super.build( builder, type );
  1515. const nodeVar = builder.getVarFromNode( this, null, type );
  1516. const propertyName = builder.getPropertyName( nodeVar );
  1517. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1518. nodeData.snippet = snippet;
  1519. nodeData.propertyName = propertyName;
  1520. return builder.format( nodeData.propertyName, type, output );
  1521. }
  1522. }
  1523. return super.build( builder, output );
  1524. }
  1525. }
  1526. /**
  1527. * This module is part of the TSL core and usually not used in app level code.
  1528. * It represents a join operation during the shader generation process.
  1529. * For example in can compose/join two single floats into a `vec2` type.
  1530. *
  1531. * @augments TempNode
  1532. */
  1533. class JoinNode extends TempNode {
  1534. static get type() {
  1535. return 'JoinNode';
  1536. }
  1537. /**
  1538. * Constructs a new join node.
  1539. *
  1540. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1541. * @param {?string} [nodeType=null] - The node type.
  1542. */
  1543. constructor( nodes = [], nodeType = null ) {
  1544. super( nodeType );
  1545. /**
  1546. * An array of nodes that should be joined.
  1547. *
  1548. * @type {Array<Node>}
  1549. */
  1550. this.nodes = nodes;
  1551. }
  1552. /**
  1553. * This method is overwritten since the node type must be inferred from the
  1554. * joined data length if not explicitly defined.
  1555. *
  1556. * @param {NodeBuilder} builder - The current node builder.
  1557. * @return {string} The node type.
  1558. */
  1559. getNodeType( builder ) {
  1560. if ( this.nodeType !== null ) {
  1561. return builder.getVectorType( this.nodeType );
  1562. }
  1563. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1564. }
  1565. generate( builder, output ) {
  1566. const type = this.getNodeType( builder );
  1567. const maxLength = builder.getTypeLength( type );
  1568. const nodes = this.nodes;
  1569. const primitiveType = builder.getComponentType( type );
  1570. const snippetValues = [];
  1571. let length = 0;
  1572. for ( const input of nodes ) {
  1573. if ( length >= maxLength ) {
  1574. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1575. break;
  1576. }
  1577. let inputType = input.getNodeType( builder );
  1578. let inputTypeLength = builder.getTypeLength( inputType );
  1579. let inputSnippet;
  1580. if ( length + inputTypeLength > maxLength ) {
  1581. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1582. inputTypeLength = maxLength - length;
  1583. inputType = builder.getTypeFromLength( inputTypeLength );
  1584. }
  1585. length += inputTypeLength;
  1586. inputSnippet = input.build( builder, inputType );
  1587. const inputPrimitiveType = builder.getComponentType( inputType );
  1588. if ( inputPrimitiveType !== primitiveType ) {
  1589. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1590. }
  1591. snippetValues.push( inputSnippet );
  1592. }
  1593. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1594. return builder.format( snippet, type, output );
  1595. }
  1596. }
  1597. const _stringVectorComponents = vectorComponents.join( '' );
  1598. /**
  1599. * This module is part of the TSL core and usually not used in app level code.
  1600. * `SplitNode` represents a property access operation which means it is
  1601. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1602. * For example:
  1603. * ```js
  1604. * const redValue = color.r;
  1605. * ```
  1606. *
  1607. * @augments Node
  1608. */
  1609. class SplitNode extends Node {
  1610. static get type() {
  1611. return 'SplitNode';
  1612. }
  1613. /**
  1614. * Constructs a new split node.
  1615. *
  1616. * @param {Node} node - The node that should be accessed.
  1617. * @param {string} [components='x'] - The components that should be accessed.
  1618. */
  1619. constructor( node, components = 'x' ) {
  1620. super();
  1621. /**
  1622. * The node that should be accessed.
  1623. *
  1624. * @type {Node}
  1625. */
  1626. this.node = node;
  1627. /**
  1628. * The components that should be accessed.
  1629. *
  1630. * @type {string}
  1631. */
  1632. this.components = components;
  1633. /**
  1634. * This flag can be used for type testing.
  1635. *
  1636. * @type {boolean}
  1637. * @readonly
  1638. * @default true
  1639. */
  1640. this.isSplitNode = true;
  1641. }
  1642. /**
  1643. * Returns the vector length which is computed based on the requested components.
  1644. *
  1645. * @return {number} The vector length.
  1646. */
  1647. getVectorLength() {
  1648. let vectorLength = this.components.length;
  1649. for ( const c of this.components ) {
  1650. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1651. }
  1652. return vectorLength;
  1653. }
  1654. /**
  1655. * Returns the component type of the node's type.
  1656. *
  1657. * @param {NodeBuilder} builder - The current node builder.
  1658. * @return {string} The component type.
  1659. */
  1660. getComponentType( builder ) {
  1661. return builder.getComponentType( this.node.getNodeType( builder ) );
  1662. }
  1663. /**
  1664. * This method is overwritten since the node type is inferred from requested components.
  1665. *
  1666. * @param {NodeBuilder} builder - The current node builder.
  1667. * @return {string} The node type.
  1668. */
  1669. getNodeType( builder ) {
  1670. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1671. }
  1672. generate( builder, output ) {
  1673. const node = this.node;
  1674. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1675. let snippet = null;
  1676. if ( nodeTypeLength > 1 ) {
  1677. let type = null;
  1678. const componentsLength = this.getVectorLength();
  1679. if ( componentsLength >= nodeTypeLength ) {
  1680. // needed expand the input node
  1681. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1682. }
  1683. const nodeSnippet = node.build( builder, type );
  1684. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1685. // unnecessary swizzle
  1686. snippet = builder.format( nodeSnippet, type, output );
  1687. } else {
  1688. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1689. }
  1690. } else {
  1691. // ignore .components if .node returns float/integer
  1692. snippet = node.build( builder, output );
  1693. }
  1694. return snippet;
  1695. }
  1696. serialize( data ) {
  1697. super.serialize( data );
  1698. data.components = this.components;
  1699. }
  1700. deserialize( data ) {
  1701. super.deserialize( data );
  1702. this.components = data.components;
  1703. }
  1704. }
  1705. /**
  1706. * This module is part of the TSL core and usually not used in app level code.
  1707. * `SetNode` represents a set operation which means it is used to implement any
  1708. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1709. * For example:
  1710. * ```js
  1711. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1712. * ```
  1713. *
  1714. * @augments TempNode
  1715. */
  1716. class SetNode extends TempNode {
  1717. static get type() {
  1718. return 'SetNode';
  1719. }
  1720. /**
  1721. * Constructs a new set node.
  1722. *
  1723. * @param {Node} sourceNode - The node that should be updated.
  1724. * @param {string} components - The components that should be updated.
  1725. * @param {Node} targetNode - The value node.
  1726. */
  1727. constructor( sourceNode, components, targetNode ) {
  1728. super();
  1729. /**
  1730. * The node that should be updated.
  1731. *
  1732. * @type {Node}
  1733. */
  1734. this.sourceNode = sourceNode;
  1735. /**
  1736. * The components that should be updated.
  1737. *
  1738. * @type {string}
  1739. */
  1740. this.components = components;
  1741. /**
  1742. * The value node.
  1743. *
  1744. * @type {Node}
  1745. */
  1746. this.targetNode = targetNode;
  1747. }
  1748. /**
  1749. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1750. *
  1751. * @param {NodeBuilder} builder - The current node builder.
  1752. * @return {string} The node type.
  1753. */
  1754. getNodeType( builder ) {
  1755. return this.sourceNode.getNodeType( builder );
  1756. }
  1757. generate( builder ) {
  1758. const { sourceNode, components, targetNode } = this;
  1759. const sourceType = this.getNodeType( builder );
  1760. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1761. const targetType = builder.getTypeFromLength( components.length, componentType );
  1762. const targetSnippet = targetNode.build( builder, targetType );
  1763. const sourceSnippet = sourceNode.build( builder, sourceType );
  1764. const length = builder.getTypeLength( sourceType );
  1765. const snippetValues = [];
  1766. for ( let i = 0; i < length; i ++ ) {
  1767. const component = vectorComponents[ i ];
  1768. if ( component === components[ 0 ] ) {
  1769. snippetValues.push( targetSnippet );
  1770. i += components.length - 1;
  1771. } else {
  1772. snippetValues.push( sourceSnippet + '.' + component );
  1773. }
  1774. }
  1775. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1776. }
  1777. }
  1778. /**
  1779. * This module is part of the TSL core and usually not used in app level code.
  1780. * It represents a flip operation during the shader generation process
  1781. * meaning it flips normalized values with the following formula:
  1782. * ```
  1783. * x = 1 - x;
  1784. * ```
  1785. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1786. * `flipSTPQ()` method invocations on node objects. For example:
  1787. * ```js
  1788. * uvNode = uvNode.flipY();
  1789. * ```
  1790. *
  1791. * @augments TempNode
  1792. */
  1793. class FlipNode extends TempNode {
  1794. static get type() {
  1795. return 'FlipNode';
  1796. }
  1797. /**
  1798. * Constructs a new flip node.
  1799. *
  1800. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1801. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1802. */
  1803. constructor( sourceNode, components ) {
  1804. super();
  1805. /**
  1806. * The node which component(s) should be flipped.
  1807. *
  1808. * @type {Node}
  1809. */
  1810. this.sourceNode = sourceNode;
  1811. /**
  1812. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1813. *
  1814. * @type {string}
  1815. */
  1816. this.components = components;
  1817. }
  1818. /**
  1819. * This method is overwritten since the node type is inferred from the source node.
  1820. *
  1821. * @param {NodeBuilder} builder - The current node builder.
  1822. * @return {string} The node type.
  1823. */
  1824. getNodeType( builder ) {
  1825. return this.sourceNode.getNodeType( builder );
  1826. }
  1827. generate( builder ) {
  1828. const { components, sourceNode } = this;
  1829. const sourceType = this.getNodeType( builder );
  1830. const sourceSnippet = sourceNode.build( builder );
  1831. const sourceCache = builder.getVarFromNode( this );
  1832. const sourceProperty = builder.getPropertyName( sourceCache );
  1833. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1834. const length = builder.getTypeLength( sourceType );
  1835. const snippetValues = [];
  1836. let componentIndex = 0;
  1837. for ( let i = 0; i < length; i ++ ) {
  1838. const component = vectorComponents[ i ];
  1839. if ( component === components[ componentIndex ] ) {
  1840. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1841. componentIndex ++;
  1842. } else {
  1843. snippetValues.push( sourceProperty + '.' + component );
  1844. }
  1845. }
  1846. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1847. }
  1848. }
  1849. /**
  1850. * Base class for representing data input nodes.
  1851. *
  1852. * @augments Node
  1853. */
  1854. class InputNode extends Node {
  1855. static get type() {
  1856. return 'InputNode';
  1857. }
  1858. /**
  1859. * Constructs a new input node.
  1860. *
  1861. * @param {any} value - The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1862. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1863. */
  1864. constructor( value, nodeType = null ) {
  1865. super( nodeType );
  1866. /**
  1867. * This flag can be used for type testing.
  1868. *
  1869. * @type {boolean}
  1870. * @readonly
  1871. * @default true
  1872. */
  1873. this.isInputNode = true;
  1874. /**
  1875. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1876. *
  1877. * @type {any}
  1878. */
  1879. this.value = value;
  1880. /**
  1881. * The precision of the value in the shader.
  1882. *
  1883. * @type {?('low'|'medium'|'high')}
  1884. * @default null
  1885. */
  1886. this.precision = null;
  1887. }
  1888. getNodeType( /*builder*/ ) {
  1889. if ( this.nodeType === null ) {
  1890. return getValueType( this.value );
  1891. }
  1892. return this.nodeType;
  1893. }
  1894. /**
  1895. * Returns the input type of the node which is by default the node type. Derived modules
  1896. * might overwrite this method and use a fixed type or compute one analytically.
  1897. *
  1898. * A typical example for different input and node types are textures. The input type of a
  1899. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1900. *
  1901. * @param {NodeBuilder} builder - The current node builder.
  1902. * @return {string} The input type.
  1903. */
  1904. getInputType( builder ) {
  1905. return this.getNodeType( builder );
  1906. }
  1907. /**
  1908. * Sets the precision to the given value. The method can be
  1909. * overwritten in derived classes if the final precision must be computed
  1910. * analytically.
  1911. *
  1912. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1913. * @return {InputNode} A reference to this node.
  1914. */
  1915. setPrecision( precision ) {
  1916. this.precision = precision;
  1917. return this;
  1918. }
  1919. serialize( data ) {
  1920. super.serialize( data );
  1921. data.value = this.value;
  1922. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1923. data.valueType = getValueType( this.value );
  1924. data.nodeType = this.nodeType;
  1925. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1926. data.precision = this.precision;
  1927. }
  1928. deserialize( data ) {
  1929. super.deserialize( data );
  1930. this.nodeType = data.nodeType;
  1931. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1932. this.precision = data.precision || null;
  1933. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1934. }
  1935. generate( /*builder, output*/ ) {
  1936. console.warn( 'Abstract function.' );
  1937. }
  1938. }
  1939. const _regNum = /float|u?int/;
  1940. /**
  1941. * Class for representing a constant value in the shader.
  1942. *
  1943. * @augments InputNode
  1944. */
  1945. class ConstNode extends InputNode {
  1946. static get type() {
  1947. return 'ConstNode';
  1948. }
  1949. /**
  1950. * Constructs a new input node.
  1951. *
  1952. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1953. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1954. */
  1955. constructor( value, nodeType = null ) {
  1956. super( value, nodeType );
  1957. /**
  1958. * This flag can be used for type testing.
  1959. *
  1960. * @type {boolean}
  1961. * @readonly
  1962. * @default true
  1963. */
  1964. this.isConstNode = true;
  1965. }
  1966. /**
  1967. * Generates the shader string of the value with the current node builder.
  1968. *
  1969. * @param {NodeBuilder} builder - The current node builder.
  1970. * @return {string} The generated value as a shader string.
  1971. */
  1972. generateConst( builder ) {
  1973. return builder.generateConst( this.getNodeType( builder ), this.value );
  1974. }
  1975. generate( builder, output ) {
  1976. const type = this.getNodeType( builder );
  1977. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  1978. return builder.generateConst( output, this.value );
  1979. }
  1980. return builder.format( this.generateConst( builder ), type, output );
  1981. }
  1982. }
  1983. /**
  1984. * Base class for representing member access on an object-like
  1985. * node data structures.
  1986. *
  1987. * @augments Node
  1988. */
  1989. class MemberNode extends Node {
  1990. static get type() {
  1991. return 'MemberNode';
  1992. }
  1993. /**
  1994. * Constructs an array element node.
  1995. *
  1996. * @param {Node} node - The array-like node.
  1997. * @param {string} property - The property name.
  1998. */
  1999. constructor( node, property ) {
  2000. super();
  2001. /**
  2002. * The array-like node.
  2003. *
  2004. * @type {Node}
  2005. */
  2006. this.node = node;
  2007. /**
  2008. * The property name.
  2009. *
  2010. * @type {Node}
  2011. */
  2012. this.property = property;
  2013. /**
  2014. * This flag can be used for type testing.
  2015. *
  2016. * @type {boolean}
  2017. * @readonly
  2018. * @default true
  2019. */
  2020. this.isMemberNode = true;
  2021. }
  2022. getNodeType( builder ) {
  2023. return this.node.getMemberType( builder, this.property );
  2024. }
  2025. generate( builder ) {
  2026. const propertyName = this.node.build( builder );
  2027. return propertyName + '.' + this.property;
  2028. }
  2029. }
  2030. let currentStack = null;
  2031. const NodeElements = new Map();
  2032. function addMethodChaining( name, nodeElement ) {
  2033. if ( NodeElements.has( name ) ) {
  2034. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2035. return;
  2036. }
  2037. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2038. NodeElements.set( name, nodeElement );
  2039. }
  2040. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2041. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2042. const shaderNodeHandler = {
  2043. setup( NodeClosure, params ) {
  2044. const inputs = params.shift();
  2045. return NodeClosure( nodeObjects( inputs ), ...params );
  2046. },
  2047. get( node, prop, nodeObj ) {
  2048. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2049. if ( node.isStackNode !== true && prop === 'assign' ) {
  2050. return ( ...params ) => {
  2051. currentStack.assign( nodeObj, ...params );
  2052. return nodeObj;
  2053. };
  2054. } else if ( NodeElements.has( prop ) ) {
  2055. const nodeElement = NodeElements.get( prop );
  2056. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2057. } else if ( prop === 'self' ) {
  2058. return node;
  2059. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2060. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2061. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2062. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2063. // accessing properties ( swizzle )
  2064. prop = parseSwizzle( prop );
  2065. return nodeObject( new SplitNode( nodeObj, prop ) );
  2066. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2067. // set properties ( swizzle ) and sort to xyzw sequence
  2068. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2069. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  2070. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2071. // set properties ( swizzle ) and sort to xyzw sequence
  2072. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2073. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2074. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2075. // accessing property
  2076. if ( prop === 'width' ) prop = 'x';
  2077. else if ( prop === 'height' ) prop = 'y';
  2078. else if ( prop === 'depth' ) prop = 'z';
  2079. return nodeObject( new SplitNode( node, prop ) );
  2080. } else if ( /^\d+$/.test( prop ) === true ) {
  2081. // accessing array
  2082. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2083. } else if ( /^get$/.test( prop ) === true ) {
  2084. // accessing properties
  2085. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2086. }
  2087. }
  2088. return Reflect.get( node, prop, nodeObj );
  2089. },
  2090. set( node, prop, value, nodeObj ) {
  2091. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2092. // setting properties
  2093. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2094. nodeObj[ prop ].assign( value );
  2095. return true;
  2096. }
  2097. }
  2098. return Reflect.set( node, prop, value, nodeObj );
  2099. }
  2100. };
  2101. const nodeObjectsCacheMap = new WeakMap();
  2102. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2103. const ShaderNodeObject = function ( obj, altType = null ) {
  2104. const type = getValueType( obj );
  2105. if ( type === 'node' ) {
  2106. let nodeObject = nodeObjectsCacheMap.get( obj );
  2107. if ( nodeObject === undefined ) {
  2108. nodeObject = new Proxy( obj, shaderNodeHandler );
  2109. nodeObjectsCacheMap.set( obj, nodeObject );
  2110. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2111. }
  2112. return nodeObject;
  2113. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2114. return nodeObject( getConstNode( obj, altType ) );
  2115. } else if ( type === 'shader' ) {
  2116. return Fn( obj );
  2117. }
  2118. return obj;
  2119. };
  2120. const ShaderNodeObjects = function ( objects, altType = null ) {
  2121. for ( const name in objects ) {
  2122. objects[ name ] = nodeObject( objects[ name ], altType );
  2123. }
  2124. return objects;
  2125. };
  2126. const ShaderNodeArray = function ( array, altType = null ) {
  2127. const len = array.length;
  2128. for ( let i = 0; i < len; i ++ ) {
  2129. array[ i ] = nodeObject( array[ i ], altType );
  2130. }
  2131. return array;
  2132. };
  2133. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2134. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2135. let fn, name = scope, minParams, maxParams;
  2136. function verifyParamsLimit( params ) {
  2137. let tslName;
  2138. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2139. else tslName = NodeClass.type;
  2140. if ( minParams !== undefined && params.length < minParams ) {
  2141. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2142. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2143. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2144. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2145. return params.slice( 0, maxParams );
  2146. }
  2147. return params;
  2148. }
  2149. if ( scope === null ) {
  2150. fn = ( ...params ) => {
  2151. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2152. };
  2153. } else if ( factor !== null ) {
  2154. factor = nodeObject( factor );
  2155. fn = ( ...params ) => {
  2156. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2157. };
  2158. } else {
  2159. fn = ( ...params ) => {
  2160. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2161. };
  2162. }
  2163. fn.setParameterLength = ( ...params ) => {
  2164. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2165. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2166. return fn;
  2167. };
  2168. fn.setName = ( value ) => {
  2169. name = value;
  2170. return fn;
  2171. };
  2172. return fn;
  2173. };
  2174. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2175. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2176. };
  2177. class ShaderCallNodeInternal extends Node {
  2178. constructor( shaderNode, inputNodes ) {
  2179. super();
  2180. this.shaderNode = shaderNode;
  2181. this.inputNodes = inputNodes;
  2182. this.isShaderCallNodeInternal = true;
  2183. }
  2184. getNodeType( builder ) {
  2185. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2186. }
  2187. getMemberType( builder, name ) {
  2188. return this.getOutputNode( builder ).getMemberType( builder, name );
  2189. }
  2190. call( builder ) {
  2191. const { shaderNode, inputNodes } = this;
  2192. const properties = builder.getNodeProperties( shaderNode );
  2193. if ( properties.onceOutput ) return properties.onceOutput;
  2194. //
  2195. let result = null;
  2196. if ( shaderNode.layout ) {
  2197. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2198. if ( functionNodesCacheMap === undefined ) {
  2199. functionNodesCacheMap = new WeakMap();
  2200. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2201. }
  2202. let functionNode = functionNodesCacheMap.get( shaderNode );
  2203. if ( functionNode === undefined ) {
  2204. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2205. functionNodesCacheMap.set( shaderNode, functionNode );
  2206. }
  2207. builder.addInclude( functionNode );
  2208. result = nodeObject( functionNode.call( inputNodes ) );
  2209. } else {
  2210. const jsFunc = shaderNode.jsFunc;
  2211. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2212. result = nodeObject( outputNode );
  2213. }
  2214. if ( shaderNode.once ) {
  2215. properties.onceOutput = result;
  2216. }
  2217. return result;
  2218. }
  2219. getOutputNode( builder ) {
  2220. const properties = builder.getNodeProperties( this );
  2221. if ( properties.outputNode === null ) {
  2222. properties.outputNode = this.setupOutput( builder );
  2223. }
  2224. return properties.outputNode;
  2225. }
  2226. setup( builder ) {
  2227. return this.getOutputNode( builder );
  2228. }
  2229. setupOutput( builder ) {
  2230. builder.addStack();
  2231. builder.stack.outputNode = this.call( builder );
  2232. return builder.removeStack();
  2233. }
  2234. generate( builder, output ) {
  2235. const outputNode = this.getOutputNode( builder );
  2236. return outputNode.build( builder, output );
  2237. }
  2238. }
  2239. class ShaderNodeInternal extends Node {
  2240. constructor( jsFunc, nodeType ) {
  2241. super( nodeType );
  2242. this.jsFunc = jsFunc;
  2243. this.layout = null;
  2244. this.global = true;
  2245. this.once = false;
  2246. }
  2247. setLayout( layout ) {
  2248. this.layout = layout;
  2249. return this;
  2250. }
  2251. call( inputs = null ) {
  2252. nodeObjects( inputs );
  2253. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2254. }
  2255. setup() {
  2256. return this.call();
  2257. }
  2258. }
  2259. const bools = [ false, true ];
  2260. const uints = [ 0, 1, 2, 3 ];
  2261. const ints = [ -1, -2 ];
  2262. 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 ];
  2263. const boolsCacheMap = new Map();
  2264. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2265. const uintsCacheMap = new Map();
  2266. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2267. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2268. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2269. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2270. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2271. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2272. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2273. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2274. const getConstNode = ( value, type ) => {
  2275. if ( constNodesCacheMap.has( value ) ) {
  2276. return constNodesCacheMap.get( value );
  2277. } else if ( value.isNode === true ) {
  2278. return value;
  2279. } else {
  2280. return new ConstNode( value, type );
  2281. }
  2282. };
  2283. const safeGetNodeType = ( node ) => {
  2284. try {
  2285. return node.getNodeType();
  2286. } catch ( _ ) {
  2287. return undefined;
  2288. }
  2289. };
  2290. const ConvertType = function ( type, cacheMap = null ) {
  2291. return ( ...params ) => {
  2292. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2293. params = [ getValueFromType( type, ...params ) ];
  2294. }
  2295. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2296. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2297. }
  2298. if ( params.length === 1 ) {
  2299. const node = getConstNode( params[ 0 ], type );
  2300. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2301. return nodeObject( new ConvertNode( node, type ) );
  2302. }
  2303. const nodes = params.map( param => getConstNode( param ) );
  2304. return nodeObject( new JoinNode( nodes, type ) );
  2305. };
  2306. };
  2307. // exports
  2308. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2309. // utils
  2310. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2311. // shader node base
  2312. function ShaderNode( jsFunc, nodeType ) {
  2313. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2314. }
  2315. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2316. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2317. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2318. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2319. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2320. let fnId = 0;
  2321. const Fn = ( jsFunc, layout = null ) => {
  2322. let nodeType = null;
  2323. if ( layout !== null ) {
  2324. if ( typeof layout === 'object' ) {
  2325. nodeType = layout.return;
  2326. } else {
  2327. if ( typeof layout === 'string' ) {
  2328. nodeType = layout;
  2329. } else {
  2330. console.error( 'THREE.TSL: Invalid layout type.' );
  2331. }
  2332. layout = null;
  2333. }
  2334. }
  2335. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2336. const fn = ( ...params ) => {
  2337. let inputs;
  2338. nodeObjects( params );
  2339. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2340. inputs = [ ...params ];
  2341. } else {
  2342. inputs = params[ 0 ];
  2343. }
  2344. const fnCall = shaderNode.call( inputs );
  2345. if ( nodeType === 'void' ) fnCall.toStack();
  2346. return fnCall;
  2347. };
  2348. fn.shaderNode = shaderNode;
  2349. fn.setLayout = ( layout ) => {
  2350. shaderNode.setLayout( layout );
  2351. return fn;
  2352. };
  2353. fn.once = () => {
  2354. shaderNode.once = true;
  2355. return fn;
  2356. };
  2357. if ( layout !== null ) {
  2358. if ( typeof layout.inputs !== 'object' ) {
  2359. const fullLayout = {
  2360. name: 'fn' + fnId ++,
  2361. type: nodeType,
  2362. inputs: []
  2363. };
  2364. for ( const name in layout ) {
  2365. if ( name === 'return' ) continue;
  2366. fullLayout.inputs.push( {
  2367. name: name,
  2368. type: layout[ name ]
  2369. } );
  2370. }
  2371. layout = fullLayout;
  2372. }
  2373. fn.setLayout( layout );
  2374. }
  2375. return fn;
  2376. };
  2377. //
  2378. addMethodChaining( 'toGlobal', ( node ) => {
  2379. node.global = true;
  2380. return node;
  2381. } );
  2382. //
  2383. const setCurrentStack = ( stack ) => {
  2384. currentStack = stack;
  2385. };
  2386. const getCurrentStack = () => currentStack;
  2387. /**
  2388. * Represent a conditional node using if/else statements.
  2389. *
  2390. * ```js
  2391. * If( condition, function )
  2392. * .ElseIf( condition, function )
  2393. * .Else( function )
  2394. * ```
  2395. * @tsl
  2396. * @function
  2397. * @param {...any} params - The parameters for the conditional node.
  2398. * @returns {StackNode} The conditional node.
  2399. */
  2400. const If = ( ...params ) => currentStack.If( ...params );
  2401. /**
  2402. * Represent a conditional node using switch/case statements.
  2403. *
  2404. * ```js
  2405. * Switch( value )
  2406. * .Case( 1, function )
  2407. * .Case( 2, 3, 4, function )
  2408. * .Default( function )
  2409. * ```
  2410. * @tsl
  2411. * @function
  2412. * @param {...any} params - The parameters for the conditional node.
  2413. * @returns {StackNode} The conditional node.
  2414. */
  2415. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2416. /**
  2417. * Add the given node to the current stack.
  2418. *
  2419. * @param {Node} node - The node to add.
  2420. * @returns {Node} The node that was added to the stack.
  2421. */
  2422. function Stack( node ) {
  2423. if ( currentStack ) currentStack.add( node );
  2424. return node;
  2425. }
  2426. addMethodChaining( 'toStack', Stack );
  2427. // types
  2428. const color = new ConvertType( 'color' );
  2429. const float = new ConvertType( 'float', cacheMaps.float );
  2430. const int = new ConvertType( 'int', cacheMaps.ints );
  2431. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2432. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2433. const vec2 = new ConvertType( 'vec2' );
  2434. const ivec2 = new ConvertType( 'ivec2' );
  2435. const uvec2 = new ConvertType( 'uvec2' );
  2436. const bvec2 = new ConvertType( 'bvec2' );
  2437. const vec3 = new ConvertType( 'vec3' );
  2438. const ivec3 = new ConvertType( 'ivec3' );
  2439. const uvec3 = new ConvertType( 'uvec3' );
  2440. const bvec3 = new ConvertType( 'bvec3' );
  2441. const vec4 = new ConvertType( 'vec4' );
  2442. const ivec4 = new ConvertType( 'ivec4' );
  2443. const uvec4 = new ConvertType( 'uvec4' );
  2444. const bvec4 = new ConvertType( 'bvec4' );
  2445. const mat2 = new ConvertType( 'mat2' );
  2446. const mat3 = new ConvertType( 'mat3' );
  2447. const mat4 = new ConvertType( 'mat4' );
  2448. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2449. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2450. addMethodChaining( 'toColor', color );
  2451. addMethodChaining( 'toFloat', float );
  2452. addMethodChaining( 'toInt', int );
  2453. addMethodChaining( 'toUint', uint );
  2454. addMethodChaining( 'toBool', bool );
  2455. addMethodChaining( 'toVec2', vec2 );
  2456. addMethodChaining( 'toIVec2', ivec2 );
  2457. addMethodChaining( 'toUVec2', uvec2 );
  2458. addMethodChaining( 'toBVec2', bvec2 );
  2459. addMethodChaining( 'toVec3', vec3 );
  2460. addMethodChaining( 'toIVec3', ivec3 );
  2461. addMethodChaining( 'toUVec3', uvec3 );
  2462. addMethodChaining( 'toBVec3', bvec3 );
  2463. addMethodChaining( 'toVec4', vec4 );
  2464. addMethodChaining( 'toIVec4', ivec4 );
  2465. addMethodChaining( 'toUVec4', uvec4 );
  2466. addMethodChaining( 'toBVec4', bvec4 );
  2467. addMethodChaining( 'toMat2', mat2 );
  2468. addMethodChaining( 'toMat3', mat3 );
  2469. addMethodChaining( 'toMat4', mat4 );
  2470. // basic nodes
  2471. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2472. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2473. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2474. addMethodChaining( 'element', element );
  2475. addMethodChaining( 'convert', convert );
  2476. // deprecated
  2477. /**
  2478. * @tsl
  2479. * @function
  2480. * @deprecated since r176. Use {@link Stack} instead.
  2481. *
  2482. * @param {Node} node - The node to add.
  2483. * @returns {Function}
  2484. */
  2485. const append = ( node ) => { // @deprecated, r176
  2486. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2487. return Stack( node );
  2488. };
  2489. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2490. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2491. return Stack( node );
  2492. } );
  2493. /**
  2494. * @tsl
  2495. * @function
  2496. * @deprecated since r168. Use {@link Fn} instead.
  2497. *
  2498. * @param {...any} params
  2499. * @returns {Function}
  2500. */
  2501. const tslFn = ( ...params ) => { // @deprecated, r168
  2502. console.warn( 'THREE.TSL: tslFn() has been renamed to Fn().' );
  2503. return Fn( ...params );
  2504. };
  2505. /**
  2506. * This class represents a shader property. It can be used
  2507. * to explicitly define a property and assign a value to it.
  2508. *
  2509. * ```js
  2510. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2511. *```
  2512. * `PropertyNode` is used by the engine to predefined common material properties
  2513. * for TSL code.
  2514. *
  2515. * @augments Node
  2516. */
  2517. class PropertyNode extends Node {
  2518. static get type() {
  2519. return 'PropertyNode';
  2520. }
  2521. /**
  2522. * Constructs a new property node.
  2523. *
  2524. * @param {string} nodeType - The type of the node.
  2525. * @param {?string} [name=null] - The name of the property in the shader.
  2526. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2527. */
  2528. constructor( nodeType, name = null, varying = false ) {
  2529. super( nodeType );
  2530. /**
  2531. * The name of the property in the shader. If no name is defined,
  2532. * the node system auto-generates one.
  2533. *
  2534. * @type {?string}
  2535. * @default null
  2536. */
  2537. this.name = name;
  2538. /**
  2539. * Whether this property is a varying or not.
  2540. *
  2541. * @type {boolean}
  2542. * @default false
  2543. */
  2544. this.varying = varying;
  2545. /**
  2546. * This flag can be used for type testing.
  2547. *
  2548. * @type {boolean}
  2549. * @readonly
  2550. * @default true
  2551. */
  2552. this.isPropertyNode = true;
  2553. }
  2554. getHash( builder ) {
  2555. return this.name || super.getHash( builder );
  2556. }
  2557. /**
  2558. * The method is overwritten so it always returns `true`.
  2559. *
  2560. * @param {NodeBuilder} builder - The current node builder.
  2561. * @return {boolean} Whether this node is global or not.
  2562. */
  2563. isGlobal( /*builder*/ ) {
  2564. return true;
  2565. }
  2566. generate( builder ) {
  2567. let nodeVar;
  2568. if ( this.varying === true ) {
  2569. nodeVar = builder.getVaryingFromNode( this, this.name );
  2570. nodeVar.needsInterpolation = true;
  2571. } else {
  2572. nodeVar = builder.getVarFromNode( this, this.name );
  2573. }
  2574. return builder.getPropertyName( nodeVar );
  2575. }
  2576. }
  2577. /**
  2578. * TSL function for creating a property node.
  2579. *
  2580. * @tsl
  2581. * @function
  2582. * @param {string} type - The type of the node.
  2583. * @param {?string} [name=null] - The name of the property in the shader.
  2584. * @returns {PropertyNode}
  2585. */
  2586. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2587. /**
  2588. * TSL function for creating a varying property node.
  2589. *
  2590. * @tsl
  2591. * @function
  2592. * @param {string} type - The type of the node.
  2593. * @param {?string} [name=null] - The name of the varying in the shader.
  2594. * @returns {PropertyNode}
  2595. */
  2596. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2597. /**
  2598. * TSL object that represents the shader variable `DiffuseColor`.
  2599. *
  2600. * @tsl
  2601. * @type {PropertyNode<vec4>}
  2602. */
  2603. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2604. /**
  2605. * TSL object that represents the shader variable `EmissiveColor`.
  2606. *
  2607. * @tsl
  2608. * @type {PropertyNode<vec3>}
  2609. */
  2610. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2611. /**
  2612. * TSL object that represents the shader variable `Roughness`.
  2613. *
  2614. * @tsl
  2615. * @type {PropertyNode<float>}
  2616. */
  2617. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2618. /**
  2619. * TSL object that represents the shader variable `Metalness`.
  2620. *
  2621. * @tsl
  2622. * @type {PropertyNode<float>}
  2623. */
  2624. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2625. /**
  2626. * TSL object that represents the shader variable `Clearcoat`.
  2627. *
  2628. * @tsl
  2629. * @type {PropertyNode<float>}
  2630. */
  2631. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2632. /**
  2633. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2634. *
  2635. * @tsl
  2636. * @type {PropertyNode<float>}
  2637. */
  2638. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2639. /**
  2640. * TSL object that represents the shader variable `Sheen`.
  2641. *
  2642. * @tsl
  2643. * @type {PropertyNode<vec3>}
  2644. */
  2645. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2646. /**
  2647. * TSL object that represents the shader variable `SheenRoughness`.
  2648. *
  2649. * @tsl
  2650. * @type {PropertyNode<float>}
  2651. */
  2652. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2653. /**
  2654. * TSL object that represents the shader variable `Iridescence`.
  2655. *
  2656. * @tsl
  2657. * @type {PropertyNode<float>}
  2658. */
  2659. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2660. /**
  2661. * TSL object that represents the shader variable `IridescenceIOR`.
  2662. *
  2663. * @tsl
  2664. * @type {PropertyNode<float>}
  2665. */
  2666. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2667. /**
  2668. * TSL object that represents the shader variable `IridescenceThickness`.
  2669. *
  2670. * @tsl
  2671. * @type {PropertyNode<float>}
  2672. */
  2673. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2674. /**
  2675. * TSL object that represents the shader variable `AlphaT`.
  2676. *
  2677. * @tsl
  2678. * @type {PropertyNode<float>}
  2679. */
  2680. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2681. /**
  2682. * TSL object that represents the shader variable `Anisotropy`.
  2683. *
  2684. * @tsl
  2685. * @type {PropertyNode<float>}
  2686. */
  2687. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2688. /**
  2689. * TSL object that represents the shader variable `AnisotropyT`.
  2690. *
  2691. * @tsl
  2692. * @type {PropertyNode<vec3>}
  2693. */
  2694. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2695. /**
  2696. * TSL object that represents the shader variable `AnisotropyB`.
  2697. *
  2698. * @tsl
  2699. * @type {PropertyNode<vec3>}
  2700. */
  2701. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2702. /**
  2703. * TSL object that represents the shader variable `SpecularColor`.
  2704. *
  2705. * @tsl
  2706. * @type {PropertyNode<color>}
  2707. */
  2708. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2709. /**
  2710. * TSL object that represents the shader variable `SpecularF90`.
  2711. *
  2712. * @tsl
  2713. * @type {PropertyNode<float>}
  2714. */
  2715. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2716. /**
  2717. * TSL object that represents the shader variable `Shininess`.
  2718. *
  2719. * @tsl
  2720. * @type {PropertyNode<float>}
  2721. */
  2722. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2723. /**
  2724. * TSL object that represents the shader variable `Output`.
  2725. *
  2726. * @tsl
  2727. * @type {PropertyNode<vec4>}
  2728. */
  2729. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2730. /**
  2731. * TSL object that represents the shader variable `dashSize`.
  2732. *
  2733. * @tsl
  2734. * @type {PropertyNode<float>}
  2735. */
  2736. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2737. /**
  2738. * TSL object that represents the shader variable `gapSize`.
  2739. *
  2740. * @tsl
  2741. * @type {PropertyNode<float>}
  2742. */
  2743. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2744. /**
  2745. * TSL object that represents the shader variable `pointWidth`.
  2746. *
  2747. * @tsl
  2748. * @type {PropertyNode<float>}
  2749. */
  2750. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2751. /**
  2752. * TSL object that represents the shader variable `IOR`.
  2753. *
  2754. * @tsl
  2755. * @type {PropertyNode<float>}
  2756. */
  2757. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2758. /**
  2759. * TSL object that represents the shader variable `Transmission`.
  2760. *
  2761. * @tsl
  2762. * @type {PropertyNode<float>}
  2763. */
  2764. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2765. /**
  2766. * TSL object that represents the shader variable `Thickness`.
  2767. *
  2768. * @tsl
  2769. * @type {PropertyNode<float>}
  2770. */
  2771. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2772. /**
  2773. * TSL object that represents the shader variable `AttenuationDistance`.
  2774. *
  2775. * @tsl
  2776. * @type {PropertyNode<float>}
  2777. */
  2778. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2779. /**
  2780. * TSL object that represents the shader variable `AttenuationColor`.
  2781. *
  2782. * @tsl
  2783. * @type {PropertyNode<color>}
  2784. */
  2785. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2786. /**
  2787. * TSL object that represents the shader variable `Dispersion`.
  2788. *
  2789. * @tsl
  2790. * @type {PropertyNode<float>}
  2791. */
  2792. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2793. /**
  2794. * This node can be used to group single instances of {@link UniformNode}
  2795. * and manage them as a uniform buffer.
  2796. *
  2797. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2798. * will be used when defining the {@link UniformNode#groupNode} property.
  2799. *
  2800. * - `objectGroup`: Uniform buffer per object.
  2801. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2802. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2803. *
  2804. * @augments Node
  2805. */
  2806. class UniformGroupNode extends Node {
  2807. static get type() {
  2808. return 'UniformGroupNode';
  2809. }
  2810. /**
  2811. * Constructs a new uniform group node.
  2812. *
  2813. * @param {string} name - The name of the uniform group node.
  2814. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2815. * @param {number} [order=1] - Influences the internal sorting.
  2816. */
  2817. constructor( name, shared = false, order = 1 ) {
  2818. super( 'string' );
  2819. /**
  2820. * The name of the uniform group node.
  2821. *
  2822. * @type {string}
  2823. */
  2824. this.name = name;
  2825. /**
  2826. * Whether this uniform group node is shared or not.
  2827. *
  2828. * @type {boolean}
  2829. * @default false
  2830. */
  2831. this.shared = shared;
  2832. /**
  2833. * Influences the internal sorting.
  2834. * TODO: Add details when this property should be changed.
  2835. *
  2836. * @type {number}
  2837. * @default 1
  2838. */
  2839. this.order = order;
  2840. /**
  2841. * This flag can be used for type testing.
  2842. *
  2843. * @type {boolean}
  2844. * @readonly
  2845. * @default true
  2846. */
  2847. this.isUniformGroup = true;
  2848. }
  2849. serialize( data ) {
  2850. super.serialize( data );
  2851. data.name = this.name;
  2852. data.version = this.version;
  2853. data.shared = this.shared;
  2854. }
  2855. deserialize( data ) {
  2856. super.deserialize( data );
  2857. this.name = data.name;
  2858. this.version = data.version;
  2859. this.shared = data.shared;
  2860. }
  2861. }
  2862. /**
  2863. * TSL function for creating a uniform group node with the given name.
  2864. *
  2865. * @tsl
  2866. * @function
  2867. * @param {string} name - The name of the uniform group node.
  2868. * @returns {UniformGroupNode}
  2869. */
  2870. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2871. /**
  2872. * TSL function for creating a shared uniform group node with the given name and order.
  2873. *
  2874. * @tsl
  2875. * @function
  2876. * @param {string} name - The name of the uniform group node.
  2877. * @param {number} [order=0] - Influences the internal sorting.
  2878. * @returns {UniformGroupNode}
  2879. */
  2880. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2881. /**
  2882. * TSL object that represents a shared uniform group node which is updated once per frame.
  2883. *
  2884. * @tsl
  2885. * @type {UniformGroupNode}
  2886. */
  2887. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2888. /**
  2889. * TSL object that represents a shared uniform group node which is updated once per render.
  2890. *
  2891. * @tsl
  2892. * @type {UniformGroupNode}
  2893. */
  2894. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2895. /**
  2896. * TSL object that represents a uniform group node which is updated once per object.
  2897. *
  2898. * @tsl
  2899. * @type {UniformGroupNode}
  2900. */
  2901. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2902. /**
  2903. * Class for representing a uniform.
  2904. *
  2905. * @augments InputNode
  2906. */
  2907. class UniformNode extends InputNode {
  2908. static get type() {
  2909. return 'UniformNode';
  2910. }
  2911. /**
  2912. * Constructs a new uniform node.
  2913. *
  2914. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2915. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2916. */
  2917. constructor( value, nodeType = null ) {
  2918. super( value, nodeType );
  2919. /**
  2920. * This flag can be used for type testing.
  2921. *
  2922. * @type {boolean}
  2923. * @readonly
  2924. * @default true
  2925. */
  2926. this.isUniformNode = true;
  2927. /**
  2928. * The name or label of the uniform.
  2929. *
  2930. * @type {string}
  2931. * @default ''
  2932. */
  2933. this.name = '';
  2934. /**
  2935. * The uniform group of this uniform. By default, uniforms are
  2936. * managed per object but they might belong to a shared group
  2937. * which is updated per frame or render call.
  2938. *
  2939. * @type {UniformGroupNode}
  2940. */
  2941. this.groupNode = objectGroup;
  2942. }
  2943. /**
  2944. * Sets the {@link UniformNode#name} property.
  2945. *
  2946. * @param {string} name - The name of the uniform.
  2947. * @return {UniformNode} A reference to this node.
  2948. */
  2949. label( name ) {
  2950. this.name = name;
  2951. return this;
  2952. }
  2953. /**
  2954. * Sets the {@link UniformNode#groupNode} property.
  2955. *
  2956. * @param {UniformGroupNode} group - The uniform group.
  2957. * @return {UniformNode} A reference to this node.
  2958. */
  2959. setGroup( group ) {
  2960. this.groupNode = group;
  2961. return this;
  2962. }
  2963. /**
  2964. * Returns the {@link UniformNode#groupNode}.
  2965. *
  2966. * @return {UniformGroupNode} The uniform group.
  2967. */
  2968. getGroup() {
  2969. return this.groupNode;
  2970. }
  2971. /**
  2972. * By default, this method returns the result of {@link Node#getHash} but derived
  2973. * classes might overwrite this method with a different implementation.
  2974. *
  2975. * @param {NodeBuilder} builder - The current node builder.
  2976. * @return {string} The uniform hash.
  2977. */
  2978. getUniformHash( builder ) {
  2979. return this.getHash( builder );
  2980. }
  2981. onUpdate( callback, updateType ) {
  2982. const self = this.getSelf();
  2983. callback = callback.bind( self );
  2984. return super.onUpdate( ( frame ) => {
  2985. const value = callback( frame, self );
  2986. if ( value !== undefined ) {
  2987. this.value = value;
  2988. }
  2989. }, updateType );
  2990. }
  2991. generate( builder, output ) {
  2992. const type = this.getNodeType( builder );
  2993. const hash = this.getUniformHash( builder );
  2994. let sharedNode = builder.getNodeFromHash( hash );
  2995. if ( sharedNode === undefined ) {
  2996. builder.setHashNode( this, hash );
  2997. sharedNode = this;
  2998. }
  2999. const sharedNodeType = sharedNode.getInputType( builder );
  3000. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  3001. const propertyName = builder.getPropertyName( nodeUniform );
  3002. if ( builder.context.label !== undefined ) delete builder.context.label;
  3003. return builder.format( propertyName, type, output );
  3004. }
  3005. }
  3006. /**
  3007. * TSL function for creating a uniform node.
  3008. *
  3009. * @tsl
  3010. * @function
  3011. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3012. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3013. * @returns {UniformNode}
  3014. */
  3015. const uniform = ( arg1, arg2 ) => {
  3016. const nodeType = getConstNodeType( arg2 || arg1 );
  3017. // @TODO: get ConstNode from .traverse() in the future
  3018. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  3019. return nodeObject( new UniformNode( value, nodeType ) );
  3020. };
  3021. /**
  3022. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3023. * ```js
  3024. * const colors = array( [
  3025. * vec3( 1, 0, 0 ),
  3026. * vec3( 0, 1, 0 ),
  3027. * vec3( 0, 0, 1 )
  3028. * ] );
  3029. *
  3030. * const redColor = tintColors.element( 0 );
  3031. *
  3032. * @augments TempNode
  3033. */
  3034. class ArrayNode extends TempNode {
  3035. static get type() {
  3036. return 'ArrayNode';
  3037. }
  3038. /**
  3039. * Constructs a new array node.
  3040. *
  3041. * @param {?string} nodeType - The data type of the elements.
  3042. * @param {number} count - Size of the array.
  3043. * @param {?Array<Node>} [values=null] - Array default values.
  3044. */
  3045. constructor( nodeType, count, values = null ) {
  3046. super( nodeType );
  3047. /**
  3048. * Array size.
  3049. *
  3050. * @type {number}
  3051. */
  3052. this.count = count;
  3053. /**
  3054. * Array default values.
  3055. *
  3056. * @type {?Array<Node>}
  3057. */
  3058. this.values = values;
  3059. /**
  3060. * This flag can be used for type testing.
  3061. *
  3062. * @type {boolean}
  3063. * @readonly
  3064. * @default true
  3065. */
  3066. this.isArrayNode = true;
  3067. }
  3068. /**
  3069. * Returns the node's type.
  3070. *
  3071. * @param {NodeBuilder} builder - The current node builder.
  3072. * @return {string} The type of the node.
  3073. */
  3074. getNodeType( builder ) {
  3075. if ( this.nodeType === null ) {
  3076. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3077. }
  3078. return this.nodeType;
  3079. }
  3080. /**
  3081. * Returns the node's type.
  3082. *
  3083. * @param {NodeBuilder} builder - The current node builder.
  3084. * @return {string} The type of the node.
  3085. */
  3086. getElementType( builder ) {
  3087. return this.getNodeType( builder );
  3088. }
  3089. /**
  3090. * This method builds the output node and returns the resulting array as a shader string.
  3091. *
  3092. * @param {NodeBuilder} builder - The current node builder.
  3093. * @return {string} The generated shader string.
  3094. */
  3095. generate( builder ) {
  3096. const type = this.getNodeType( builder );
  3097. return builder.generateArray( type, this.count, this.values );
  3098. }
  3099. }
  3100. /**
  3101. * TSL function for creating an array node.
  3102. *
  3103. * @tsl
  3104. * @function
  3105. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3106. * or an array containing the default values (e.g., [ vec3() ]).
  3107. * @param {?number} [count] - Size of the array.
  3108. * @returns {ArrayNode}
  3109. */
  3110. const array = ( ...params ) => {
  3111. let node;
  3112. if ( params.length === 1 ) {
  3113. const values = params[ 0 ];
  3114. node = new ArrayNode( null, values.length, values );
  3115. } else {
  3116. const nodeType = params[ 0 ];
  3117. const count = params[ 1 ];
  3118. node = new ArrayNode( nodeType, count );
  3119. }
  3120. return nodeObject( node );
  3121. };
  3122. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3123. /**
  3124. * These node represents an assign operation. Meaning a node is assigned
  3125. * to another node.
  3126. *
  3127. * @augments TempNode
  3128. */
  3129. class AssignNode extends TempNode {
  3130. static get type() {
  3131. return 'AssignNode';
  3132. }
  3133. /**
  3134. * Constructs a new assign node.
  3135. *
  3136. * @param {Node} targetNode - The target node.
  3137. * @param {Node} sourceNode - The source type.
  3138. */
  3139. constructor( targetNode, sourceNode ) {
  3140. super();
  3141. /**
  3142. * The target node.
  3143. *
  3144. * @type {Node}
  3145. */
  3146. this.targetNode = targetNode;
  3147. /**
  3148. * The source node.
  3149. *
  3150. * @type {Node}
  3151. */
  3152. this.sourceNode = sourceNode;
  3153. }
  3154. /**
  3155. * Whether this node is used more than once in context of other nodes. This method
  3156. * is overwritten since it always returns `false` (assigns are unique).
  3157. *
  3158. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3159. */
  3160. hasDependencies() {
  3161. return false;
  3162. }
  3163. getNodeType( builder, output ) {
  3164. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3165. }
  3166. /**
  3167. * Whether a split is required when assigning source to target. This can happen when the component length of
  3168. * target and source data type does not match.
  3169. *
  3170. * @param {NodeBuilder} builder - The current node builder.
  3171. * @return {boolean} Whether a split is required when assigning source to target.
  3172. */
  3173. needsSplitAssign( builder ) {
  3174. const { targetNode } = this;
  3175. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3176. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3177. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3178. return assignDifferentVector;
  3179. }
  3180. return false;
  3181. }
  3182. generate( builder, output ) {
  3183. const { targetNode, sourceNode } = this;
  3184. const needsSplitAssign = this.needsSplitAssign( builder );
  3185. const targetType = targetNode.getNodeType( builder );
  3186. const target = targetNode.context( { assign: true } ).build( builder );
  3187. const source = sourceNode.build( builder, targetType );
  3188. const sourceType = sourceNode.getNodeType( builder );
  3189. const nodeData = builder.getDataFromNode( this );
  3190. //
  3191. let snippet;
  3192. if ( nodeData.initialized === true ) {
  3193. if ( output !== 'void' ) {
  3194. snippet = target;
  3195. }
  3196. } else if ( needsSplitAssign ) {
  3197. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3198. const sourceProperty = builder.getPropertyName( sourceVar );
  3199. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3200. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  3201. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  3202. const component = targetNode.components[ i ];
  3203. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3204. }
  3205. if ( output !== 'void' ) {
  3206. snippet = target;
  3207. }
  3208. } else {
  3209. snippet = `${ target } = ${ source }`;
  3210. if ( output === 'void' || sourceType === 'void' ) {
  3211. builder.addLineFlowCode( snippet, this );
  3212. if ( output !== 'void' ) {
  3213. snippet = target;
  3214. }
  3215. }
  3216. }
  3217. nodeData.initialized = true;
  3218. return builder.format( snippet, targetType, output );
  3219. }
  3220. }
  3221. /**
  3222. * TSL function for creating an assign node.
  3223. *
  3224. * @tsl
  3225. * @function
  3226. * @param {Node} targetNode - The target node.
  3227. * @param {Node} sourceNode - The source type.
  3228. * @returns {AssignNode}
  3229. */
  3230. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3231. addMethodChaining( 'assign', assign );
  3232. /**
  3233. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3234. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3235. * this logic.
  3236. *
  3237. * @augments TempNode
  3238. */
  3239. class FunctionCallNode extends TempNode {
  3240. static get type() {
  3241. return 'FunctionCallNode';
  3242. }
  3243. /**
  3244. * Constructs a new function call node.
  3245. *
  3246. * @param {?FunctionNode} functionNode - The function node.
  3247. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3248. */
  3249. constructor( functionNode = null, parameters = {} ) {
  3250. super();
  3251. /**
  3252. * The function node.
  3253. *
  3254. * @type {?FunctionNode}
  3255. * @default null
  3256. */
  3257. this.functionNode = functionNode;
  3258. /**
  3259. * The parameters of the function call.
  3260. *
  3261. * @type {Object<string, Node>}
  3262. * @default {}
  3263. */
  3264. this.parameters = parameters;
  3265. }
  3266. /**
  3267. * Sets the parameters of the function call node.
  3268. *
  3269. * @param {Object<string, Node>} parameters - The parameters to set.
  3270. * @return {FunctionCallNode} A reference to this node.
  3271. */
  3272. setParameters( parameters ) {
  3273. this.parameters = parameters;
  3274. return this;
  3275. }
  3276. /**
  3277. * Returns the parameters of the function call node.
  3278. *
  3279. * @return {Object<string, Node>} The parameters of this node.
  3280. */
  3281. getParameters() {
  3282. return this.parameters;
  3283. }
  3284. getNodeType( builder ) {
  3285. return this.functionNode.getNodeType( builder );
  3286. }
  3287. generate( builder ) {
  3288. const params = [];
  3289. const functionNode = this.functionNode;
  3290. const inputs = functionNode.getInputs( builder );
  3291. const parameters = this.parameters;
  3292. const generateInput = ( node, inputNode ) => {
  3293. const type = inputNode.type;
  3294. const pointer = type === 'pointer';
  3295. let output;
  3296. if ( pointer ) output = '&' + node.build( builder );
  3297. else output = node.build( builder, type );
  3298. return output;
  3299. };
  3300. if ( Array.isArray( parameters ) ) {
  3301. if ( parameters.length > inputs.length ) {
  3302. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3303. parameters.length = inputs.length;
  3304. } else if ( parameters.length < inputs.length ) {
  3305. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3306. while ( parameters.length < inputs.length ) {
  3307. parameters.push( float( 0 ) );
  3308. }
  3309. }
  3310. for ( let i = 0; i < parameters.length; i ++ ) {
  3311. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3312. }
  3313. } else {
  3314. for ( const inputNode of inputs ) {
  3315. const node = parameters[ inputNode.name ];
  3316. if ( node !== undefined ) {
  3317. params.push( generateInput( node, inputNode ) );
  3318. } else {
  3319. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3320. params.push( generateInput( float( 0 ), inputNode ) );
  3321. }
  3322. }
  3323. }
  3324. const functionName = functionNode.build( builder, 'property' );
  3325. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3326. }
  3327. }
  3328. const call = ( func, ...params ) => {
  3329. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3330. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3331. };
  3332. addMethodChaining( 'call', call );
  3333. const _vectorOperators = {
  3334. '==': 'equal',
  3335. '!=': 'notEqual',
  3336. '<': 'lessThan',
  3337. '>': 'greaterThan',
  3338. '<=': 'lessThanEqual',
  3339. '>=': 'greaterThanEqual',
  3340. '%': 'mod'
  3341. };
  3342. /**
  3343. * This node represents basic mathematical and logical operations like addition,
  3344. * subtraction or comparisons (e.g. `equal()`).
  3345. *
  3346. * @augments TempNode
  3347. */
  3348. class OperatorNode extends TempNode {
  3349. static get type() {
  3350. return 'OperatorNode';
  3351. }
  3352. /**
  3353. * Constructs a new operator node.
  3354. *
  3355. * @param {string} op - The operator.
  3356. * @param {Node} aNode - The first input.
  3357. * @param {Node} bNode - The second input.
  3358. * @param {...Node} params - Additional input parameters.
  3359. */
  3360. constructor( op, aNode, bNode, ...params ) {
  3361. super();
  3362. if ( params.length > 0 ) {
  3363. let finalOp = new OperatorNode( op, aNode, bNode );
  3364. for ( let i = 0; i < params.length - 1; i ++ ) {
  3365. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3366. }
  3367. aNode = finalOp;
  3368. bNode = params[ params.length - 1 ];
  3369. }
  3370. /**
  3371. * The operator.
  3372. *
  3373. * @type {string}
  3374. */
  3375. this.op = op;
  3376. /**
  3377. * The first input.
  3378. *
  3379. * @type {Node}
  3380. */
  3381. this.aNode = aNode;
  3382. /**
  3383. * The second input.
  3384. *
  3385. * @type {Node}
  3386. */
  3387. this.bNode = bNode;
  3388. /**
  3389. * This flag can be used for type testing.
  3390. *
  3391. * @type {boolean}
  3392. * @readonly
  3393. * @default true
  3394. */
  3395. this.isOperatorNode = true;
  3396. }
  3397. /**
  3398. * Returns the operator method name.
  3399. *
  3400. * @param {NodeBuilder} builder - The current node builder.
  3401. * @param {string} output - The output type.
  3402. * @returns {string} The operator method name.
  3403. */
  3404. getOperatorMethod( builder, output ) {
  3405. return builder.getMethod( _vectorOperators[ this.op ], output );
  3406. }
  3407. /**
  3408. * This method is overwritten since the node type is inferred from the operator
  3409. * and the input node types.
  3410. *
  3411. * @param {NodeBuilder} builder - The current node builder.
  3412. * @return {string} The node type.
  3413. */
  3414. getNodeType( builder ) {
  3415. const op = this.op;
  3416. const aNode = this.aNode;
  3417. const bNode = this.bNode;
  3418. const typeA = aNode.getNodeType( builder );
  3419. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3420. if ( typeA === 'void' || typeB === 'void' ) {
  3421. return 'void';
  3422. } else if ( op === '%' ) {
  3423. return typeA;
  3424. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3425. return builder.getIntegerType( typeA );
  3426. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3427. return 'bool';
  3428. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3429. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3430. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3431. } else {
  3432. // Handle matrix operations
  3433. if ( builder.isMatrix( typeA ) ) {
  3434. if ( typeB === 'float' ) {
  3435. return typeA; // matrix * scalar = matrix
  3436. } else if ( builder.isVector( typeB ) ) {
  3437. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3438. } else if ( builder.isMatrix( typeB ) ) {
  3439. return typeA; // matrix * matrix
  3440. }
  3441. } else if ( builder.isMatrix( typeB ) ) {
  3442. if ( typeA === 'float' ) {
  3443. return typeB; // scalar * matrix = matrix
  3444. } else if ( builder.isVector( typeA ) ) {
  3445. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3446. }
  3447. }
  3448. // Handle non-matrix cases
  3449. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3450. // anytype x anytype: use the greater length vector
  3451. return typeB;
  3452. }
  3453. return typeA;
  3454. }
  3455. }
  3456. generate( builder, output ) {
  3457. const op = this.op;
  3458. const aNode = this.aNode;
  3459. const bNode = this.bNode;
  3460. const type = this.getNodeType( builder );
  3461. let typeA = null;
  3462. let typeB = null;
  3463. if ( type !== 'void' ) {
  3464. typeA = aNode.getNodeType( builder );
  3465. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3466. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3467. if ( builder.isVector( typeA ) ) {
  3468. typeB = typeA;
  3469. } else if ( builder.isVector( typeB ) ) {
  3470. typeA = typeB;
  3471. } else if ( typeA !== typeB ) {
  3472. typeA = typeB = 'float';
  3473. }
  3474. } else if ( op === '>>' || op === '<<' ) {
  3475. typeA = type;
  3476. typeB = builder.changeComponentType( typeB, 'uint' );
  3477. } else if ( op === '%' ) {
  3478. typeA = type;
  3479. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3480. } else if ( builder.isMatrix( typeA ) ) {
  3481. if ( typeB === 'float' ) {
  3482. // Keep matrix type for typeA, but ensure typeB stays float
  3483. typeB = 'float';
  3484. } else if ( builder.isVector( typeB ) ) {
  3485. // matrix x vector
  3486. typeB = builder.getVectorFromMatrix( typeA );
  3487. } else if ( builder.isMatrix( typeB ) ) ; else {
  3488. typeA = typeB = type;
  3489. }
  3490. } else if ( builder.isMatrix( typeB ) ) {
  3491. if ( typeA === 'float' ) {
  3492. // Keep matrix type for typeB, but ensure typeA stays float
  3493. typeA = 'float';
  3494. } else if ( builder.isVector( typeA ) ) {
  3495. // vector x matrix
  3496. typeA = builder.getVectorFromMatrix( typeB );
  3497. } else {
  3498. typeA = typeB = type;
  3499. }
  3500. } else {
  3501. // anytype x anytype
  3502. typeA = typeB = type;
  3503. }
  3504. } else {
  3505. typeA = typeB = type;
  3506. }
  3507. const a = aNode.build( builder, typeA );
  3508. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3509. const fnOpSnippet = builder.getFunctionOperator( op );
  3510. if ( output !== 'void' ) {
  3511. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3512. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3513. if ( isGLSL ) {
  3514. if ( builder.isVector( typeA ) ) {
  3515. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3516. } else {
  3517. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3518. }
  3519. } else {
  3520. // WGSL
  3521. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3522. }
  3523. } else if ( op === '%' ) {
  3524. if ( builder.isInteger( typeB ) ) {
  3525. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3526. } else {
  3527. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3528. }
  3529. } else if ( op === '!' || op === '~' ) {
  3530. return builder.format( `(${op}${a})`, typeA, output );
  3531. } else if ( fnOpSnippet ) {
  3532. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3533. } else {
  3534. // Handle matrix operations
  3535. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3536. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3537. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3538. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3539. } else {
  3540. let snippet = `( ${ a } ${ op } ${ b } )`;
  3541. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3542. snippet = `all${ snippet }`;
  3543. }
  3544. return builder.format( snippet, type, output );
  3545. }
  3546. }
  3547. } else if ( typeA !== 'void' ) {
  3548. if ( fnOpSnippet ) {
  3549. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3550. } else {
  3551. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3552. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3553. } else {
  3554. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3555. }
  3556. }
  3557. }
  3558. }
  3559. serialize( data ) {
  3560. super.serialize( data );
  3561. data.op = this.op;
  3562. }
  3563. deserialize( data ) {
  3564. super.deserialize( data );
  3565. this.op = data.op;
  3566. }
  3567. }
  3568. /**
  3569. * Returns the addition of two or more value.
  3570. *
  3571. * @tsl
  3572. * @function
  3573. * @param {Node} a - The first input.
  3574. * @param {Node} b - The second input.
  3575. * @param {...Node} params - Additional input parameters.
  3576. * @returns {OperatorNode}
  3577. */
  3578. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3579. /**
  3580. * Returns the subtraction of two or more value.
  3581. *
  3582. * @tsl
  3583. * @function
  3584. * @param {Node} a - The first input.
  3585. * @param {Node} b - The second input.
  3586. * @param {...Node} params - Additional input parameters.
  3587. * @returns {OperatorNode}
  3588. */
  3589. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3590. /**
  3591. * Returns the multiplication of two or more value.
  3592. *
  3593. * @tsl
  3594. * @function
  3595. * @param {Node} a - The first input.
  3596. * @param {Node} b - The second input.
  3597. * @param {...Node} params - Additional input parameters.
  3598. * @returns {OperatorNode}
  3599. */
  3600. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3601. /**
  3602. * Returns the division of two or more value.
  3603. *
  3604. * @tsl
  3605. * @function
  3606. * @param {Node} a - The first input.
  3607. * @param {Node} b - The second input.
  3608. * @param {...Node} params - Additional input parameters.
  3609. * @returns {OperatorNode}
  3610. */
  3611. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3612. /**
  3613. * Computes the remainder of dividing the first node by the second one.
  3614. *
  3615. * @tsl
  3616. * @function
  3617. * @param {Node} a - The first input.
  3618. * @param {Node} b - The second input.
  3619. * @returns {OperatorNode}
  3620. */
  3621. const mod = /*@__PURE__*/ nodeProxy( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3622. /**
  3623. * Checks if two nodes are equal.
  3624. *
  3625. * @tsl
  3626. * @function
  3627. * @param {Node} a - The first input.
  3628. * @param {Node} b - The second input.
  3629. * @returns {OperatorNode}
  3630. */
  3631. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3632. /**
  3633. * Checks if two nodes are not equal.
  3634. *
  3635. * @tsl
  3636. * @function
  3637. * @param {Node} a - The first input.
  3638. * @param {Node} b - The second input.
  3639. * @returns {OperatorNode}
  3640. */
  3641. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3642. /**
  3643. * Checks if the first node is less than the second.
  3644. *
  3645. * @tsl
  3646. * @function
  3647. * @param {Node} a - The first input.
  3648. * @param {Node} b - The second input.
  3649. * @returns {OperatorNode}
  3650. */
  3651. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3652. /**
  3653. * Checks if the first node is greater than the second.
  3654. *
  3655. * @tsl
  3656. * @function
  3657. * @param {Node} a - The first input.
  3658. * @param {Node} b - The second input.
  3659. * @returns {OperatorNode}
  3660. */
  3661. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3662. /**
  3663. * Checks if the first node is less than or equal to the second.
  3664. *
  3665. * @tsl
  3666. * @function
  3667. * @param {Node} a - The first input.
  3668. * @param {Node} b - The second input.
  3669. * @returns {OperatorNode}
  3670. */
  3671. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3672. /**
  3673. * Checks if the first node is greater than or equal to the second.
  3674. *
  3675. * @tsl
  3676. * @function
  3677. * @param {Node} a - The first input.
  3678. * @param {Node} b - The second input.
  3679. * @returns {OperatorNode}
  3680. */
  3681. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  3682. /**
  3683. * Performs a logical AND operation on multiple nodes.
  3684. *
  3685. * @tsl
  3686. * @function
  3687. * @param {...Node} nodes - The input nodes to be combined using AND.
  3688. * @returns {OperatorNode}
  3689. */
  3690. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  3691. /**
  3692. * Performs a logical OR operation on multiple nodes.
  3693. *
  3694. * @tsl
  3695. * @function
  3696. * @param {...Node} nodes - The input nodes to be combined using OR.
  3697. * @returns {OperatorNode}
  3698. */
  3699. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  3700. /**
  3701. * Performs logical NOT on a node.
  3702. *
  3703. * @tsl
  3704. * @function
  3705. * @param {Node} value - The value.
  3706. * @returns {OperatorNode}
  3707. */
  3708. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  3709. /**
  3710. * Performs logical XOR on two nodes.
  3711. *
  3712. * @tsl
  3713. * @function
  3714. * @param {Node} a - The first input.
  3715. * @param {Node} b - The second input.
  3716. * @returns {OperatorNode}
  3717. */
  3718. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  3719. /**
  3720. * Performs bitwise AND on two nodes.
  3721. *
  3722. * @tsl
  3723. * @function
  3724. * @param {Node} a - The first input.
  3725. * @param {Node} b - The second input.
  3726. * @returns {OperatorNode}
  3727. */
  3728. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  3729. /**
  3730. * Performs bitwise NOT on a node.
  3731. *
  3732. * @tsl
  3733. * @function
  3734. * @param {Node} a - The first input.
  3735. * @param {Node} b - The second input.
  3736. * @returns {OperatorNode}
  3737. */
  3738. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  3739. /**
  3740. * Performs bitwise OR on two nodes.
  3741. *
  3742. * @tsl
  3743. * @function
  3744. * @param {Node} a - The first input.
  3745. * @param {Node} b - The second input.
  3746. * @returns {OperatorNode}
  3747. */
  3748. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  3749. /**
  3750. * Performs bitwise XOR on two nodes.
  3751. *
  3752. * @tsl
  3753. * @function
  3754. * @param {Node} a - The first input.
  3755. * @param {Node} b - The second input.
  3756. * @returns {OperatorNode}
  3757. */
  3758. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  3759. /**
  3760. * Shifts a node to the left.
  3761. *
  3762. * @tsl
  3763. * @function
  3764. * @param {Node} a - The node to shift.
  3765. * @param {Node} b - The value to shift.
  3766. * @returns {OperatorNode}
  3767. */
  3768. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  3769. /**
  3770. * Shifts a node to the right.
  3771. *
  3772. * @tsl
  3773. * @function
  3774. * @param {Node} a - The node to shift.
  3775. * @param {Node} b - The value to shift.
  3776. * @returns {OperatorNode}
  3777. */
  3778. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  3779. /**
  3780. * Increments a node by 1.
  3781. *
  3782. * @tsl
  3783. * @function
  3784. * @param {Node} a - The node to increment.
  3785. * @returns {OperatorNode}
  3786. */
  3787. const incrementBefore = Fn( ( [ a ] ) => {
  3788. a.addAssign( 1 );
  3789. return a;
  3790. } );
  3791. /**
  3792. * Decrements a node by 1.
  3793. *
  3794. * @tsl
  3795. * @function
  3796. * @param {Node} a - The node to decrement.
  3797. * @returns {OperatorNode}
  3798. */
  3799. const decrementBefore = Fn( ( [ a ] ) => {
  3800. a.subAssign( 1 );
  3801. return a;
  3802. } );
  3803. /**
  3804. * Increments a node by 1 and returns the previous value.
  3805. *
  3806. * @tsl
  3807. * @function
  3808. * @param {Node} a - The node to increment.
  3809. * @returns {OperatorNode}
  3810. */
  3811. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3812. const temp = int( a ).toConst();
  3813. a.addAssign( 1 );
  3814. return temp;
  3815. } );
  3816. /**
  3817. * Decrements a node by 1 and returns the previous value.
  3818. *
  3819. * @tsl
  3820. * @function
  3821. * @param {Node} a - The node to decrement.
  3822. * @returns {OperatorNode}
  3823. */
  3824. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3825. const temp = int( a ).toConst();
  3826. a.subAssign( 1 );
  3827. return temp;
  3828. } );
  3829. addMethodChaining( 'add', add );
  3830. addMethodChaining( 'sub', sub );
  3831. addMethodChaining( 'mul', mul );
  3832. addMethodChaining( 'div', div );
  3833. addMethodChaining( 'mod', mod );
  3834. addMethodChaining( 'equal', equal );
  3835. addMethodChaining( 'notEqual', notEqual );
  3836. addMethodChaining( 'lessThan', lessThan );
  3837. addMethodChaining( 'greaterThan', greaterThan );
  3838. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3839. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3840. addMethodChaining( 'and', and );
  3841. addMethodChaining( 'or', or );
  3842. addMethodChaining( 'not', not );
  3843. addMethodChaining( 'xor', xor );
  3844. addMethodChaining( 'bitAnd', bitAnd );
  3845. addMethodChaining( 'bitNot', bitNot );
  3846. addMethodChaining( 'bitOr', bitOr );
  3847. addMethodChaining( 'bitXor', bitXor );
  3848. addMethodChaining( 'shiftLeft', shiftLeft );
  3849. addMethodChaining( 'shiftRight', shiftRight );
  3850. addMethodChaining( 'incrementBefore', incrementBefore );
  3851. addMethodChaining( 'decrementBefore', decrementBefore );
  3852. addMethodChaining( 'increment', increment );
  3853. addMethodChaining( 'decrement', decrement );
  3854. /**
  3855. * @tsl
  3856. * @function
  3857. * @deprecated since r168. Use {@link mod} instead.
  3858. *
  3859. * @param {Node} a - The first input.
  3860. * @param {Node} b - The second input.
  3861. * @returns {OperatorNode}
  3862. */
  3863. const remainder = ( a, b ) => { // @deprecated, r168
  3864. console.warn( 'THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3865. return mod( a, b );
  3866. };
  3867. /**
  3868. * @tsl
  3869. * @function
  3870. * @deprecated since r175. Use {@link mod} instead.
  3871. *
  3872. * @param {Node} a - The first input.
  3873. * @param {Node} b - The second input.
  3874. * @returns {OperatorNode}
  3875. */
  3876. const modInt = ( a, b ) => { // @deprecated, r175
  3877. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3878. return mod( int( a ), int( b ) );
  3879. };
  3880. addMethodChaining( 'remainder', remainder );
  3881. addMethodChaining( 'modInt', modInt );
  3882. /**
  3883. * This node represents a variety of mathematical methods available in shaders.
  3884. * They are divided into three categories:
  3885. *
  3886. * - Methods with one input like `sin`, `cos` or `normalize`.
  3887. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3888. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3889. *
  3890. * @augments TempNode
  3891. */
  3892. class MathNode extends TempNode {
  3893. static get type() {
  3894. return 'MathNode';
  3895. }
  3896. /**
  3897. * Constructs a new math node.
  3898. *
  3899. * @param {string} method - The method name.
  3900. * @param {Node} aNode - The first input.
  3901. * @param {?Node} [bNode=null] - The second input.
  3902. * @param {?Node} [cNode=null] - The third input.
  3903. */
  3904. constructor( method, aNode, bNode = null, cNode = null ) {
  3905. super();
  3906. // Allow the max() and min() functions to take an arbitrary number of arguments.
  3907. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  3908. let finalOp = new MathNode( method, aNode, bNode );
  3909. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  3910. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  3911. }
  3912. aNode = finalOp;
  3913. bNode = arguments[ arguments.length - 1 ];
  3914. cNode = null;
  3915. }
  3916. /**
  3917. * The method name.
  3918. *
  3919. * @type {string}
  3920. */
  3921. this.method = method;
  3922. /**
  3923. * The first input.
  3924. *
  3925. * @type {Node}
  3926. */
  3927. this.aNode = aNode;
  3928. /**
  3929. * The second input.
  3930. *
  3931. * @type {?Node}
  3932. * @default null
  3933. */
  3934. this.bNode = bNode;
  3935. /**
  3936. * The third input.
  3937. *
  3938. * @type {?Node}
  3939. * @default null
  3940. */
  3941. this.cNode = cNode;
  3942. /**
  3943. * This flag can be used for type testing.
  3944. *
  3945. * @type {boolean}
  3946. * @readonly
  3947. * @default true
  3948. */
  3949. this.isMathNode = true;
  3950. }
  3951. /**
  3952. * The input type is inferred from the node types of the input nodes.
  3953. *
  3954. * @param {NodeBuilder} builder - The current node builder.
  3955. * @return {string} The input type.
  3956. */
  3957. getInputType( builder ) {
  3958. const aType = this.aNode.getNodeType( builder );
  3959. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3960. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3961. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3962. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3963. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3964. if ( aLen > bLen && aLen > cLen ) {
  3965. return aType;
  3966. } else if ( bLen > cLen ) {
  3967. return bType;
  3968. } else if ( cLen > aLen ) {
  3969. return cType;
  3970. }
  3971. return aType;
  3972. }
  3973. /**
  3974. * The selected method as well as the input type determine the node type of this node.
  3975. *
  3976. * @param {NodeBuilder} builder - The current node builder.
  3977. * @return {string} The node type.
  3978. */
  3979. getNodeType( builder ) {
  3980. const method = this.method;
  3981. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3982. return 'float';
  3983. } else if ( method === MathNode.CROSS ) {
  3984. return 'vec3';
  3985. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  3986. return 'bool';
  3987. } else if ( method === MathNode.EQUALS ) {
  3988. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3989. } else {
  3990. return this.getInputType( builder );
  3991. }
  3992. }
  3993. generate( builder, output ) {
  3994. let method = this.method;
  3995. const type = this.getNodeType( builder );
  3996. const inputType = this.getInputType( builder );
  3997. const a = this.aNode;
  3998. const b = this.bNode;
  3999. const c = this.cNode;
  4000. const coordinateSystem = builder.renderer.coordinateSystem;
  4001. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4002. // dir can be either a direction vector or a normal vector
  4003. // upper-left 3x3 of matrix is assumed to be orthogonal
  4004. let tA = a;
  4005. let tB = b;
  4006. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4007. tB = vec4( vec3( tB ), 0.0 );
  4008. } else {
  4009. tA = vec4( vec3( tA ), 0.0 );
  4010. }
  4011. const mulNode = mul( tA, tB ).xyz;
  4012. return normalize( mulNode ).build( builder, output );
  4013. } else if ( method === MathNode.NEGATE ) {
  4014. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4015. } else if ( method === MathNode.ONE_MINUS ) {
  4016. return sub( 1.0, a ).build( builder, output );
  4017. } else if ( method === MathNode.RECIPROCAL ) {
  4018. return div( 1.0, a ).build( builder, output );
  4019. } else if ( method === MathNode.DIFFERENCE ) {
  4020. return abs( sub( a, b ) ).build( builder, output );
  4021. } else {
  4022. const params = [];
  4023. if ( method === MathNode.CROSS ) {
  4024. params.push(
  4025. a.build( builder, type ),
  4026. b.build( builder, type )
  4027. );
  4028. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4029. params.push(
  4030. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4031. b.build( builder, inputType )
  4032. );
  4033. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4034. params.push(
  4035. a.build( builder, inputType ),
  4036. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4037. );
  4038. } else if ( method === MathNode.REFRACT ) {
  4039. params.push(
  4040. a.build( builder, inputType ),
  4041. b.build( builder, inputType ),
  4042. c.build( builder, 'float' )
  4043. );
  4044. } else if ( method === MathNode.MIX ) {
  4045. params.push(
  4046. a.build( builder, inputType ),
  4047. b.build( builder, inputType ),
  4048. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4049. );
  4050. } else {
  4051. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4052. method = 'atan2';
  4053. }
  4054. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4055. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4056. method = '/*' + method + '*/';
  4057. }
  4058. params.push( a.build( builder, inputType ) );
  4059. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4060. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4061. }
  4062. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4063. }
  4064. }
  4065. serialize( data ) {
  4066. super.serialize( data );
  4067. data.method = this.method;
  4068. }
  4069. deserialize( data ) {
  4070. super.deserialize( data );
  4071. this.method = data.method;
  4072. }
  4073. }
  4074. // 1 input
  4075. MathNode.ALL = 'all';
  4076. MathNode.ANY = 'any';
  4077. MathNode.RADIANS = 'radians';
  4078. MathNode.DEGREES = 'degrees';
  4079. MathNode.EXP = 'exp';
  4080. MathNode.EXP2 = 'exp2';
  4081. MathNode.LOG = 'log';
  4082. MathNode.LOG2 = 'log2';
  4083. MathNode.SQRT = 'sqrt';
  4084. MathNode.INVERSE_SQRT = 'inversesqrt';
  4085. MathNode.FLOOR = 'floor';
  4086. MathNode.CEIL = 'ceil';
  4087. MathNode.NORMALIZE = 'normalize';
  4088. MathNode.FRACT = 'fract';
  4089. MathNode.SIN = 'sin';
  4090. MathNode.COS = 'cos';
  4091. MathNode.TAN = 'tan';
  4092. MathNode.ASIN = 'asin';
  4093. MathNode.ACOS = 'acos';
  4094. MathNode.ATAN = 'atan';
  4095. MathNode.ABS = 'abs';
  4096. MathNode.SIGN = 'sign';
  4097. MathNode.LENGTH = 'length';
  4098. MathNode.NEGATE = 'negate';
  4099. MathNode.ONE_MINUS = 'oneMinus';
  4100. MathNode.DFDX = 'dFdx';
  4101. MathNode.DFDY = 'dFdy';
  4102. MathNode.ROUND = 'round';
  4103. MathNode.RECIPROCAL = 'reciprocal';
  4104. MathNode.TRUNC = 'trunc';
  4105. MathNode.FWIDTH = 'fwidth';
  4106. MathNode.TRANSPOSE = 'transpose';
  4107. // 2 inputs
  4108. MathNode.BITCAST = 'bitcast';
  4109. MathNode.EQUALS = 'equals';
  4110. MathNode.MIN = 'min';
  4111. MathNode.MAX = 'max';
  4112. MathNode.STEP = 'step';
  4113. MathNode.REFLECT = 'reflect';
  4114. MathNode.DISTANCE = 'distance';
  4115. MathNode.DIFFERENCE = 'difference';
  4116. MathNode.DOT = 'dot';
  4117. MathNode.CROSS = 'cross';
  4118. MathNode.POW = 'pow';
  4119. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4120. // 3 inputs
  4121. MathNode.MIX = 'mix';
  4122. MathNode.CLAMP = 'clamp';
  4123. MathNode.REFRACT = 'refract';
  4124. MathNode.SMOOTHSTEP = 'smoothstep';
  4125. MathNode.FACEFORWARD = 'faceforward';
  4126. // 1 inputs
  4127. /**
  4128. * A small value used to handle floating-point precision errors.
  4129. *
  4130. * @tsl
  4131. * @type {Node<float>}
  4132. */
  4133. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4134. /**
  4135. * Represents infinity.
  4136. *
  4137. * @tsl
  4138. * @type {Node<float>}
  4139. */
  4140. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4141. /**
  4142. * Represents PI.
  4143. *
  4144. * @tsl
  4145. * @type {Node<float>}
  4146. */
  4147. const PI = /*@__PURE__*/ float( Math.PI );
  4148. /**
  4149. * Represents PI * 2.
  4150. *
  4151. * @tsl
  4152. * @type {Node<float>}
  4153. */
  4154. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4155. /**
  4156. * Returns `true` if all components of `x` are `true`.
  4157. *
  4158. * @tsl
  4159. * @function
  4160. * @param {Node | number} x - The parameter.
  4161. * @returns {Node<bool>}
  4162. */
  4163. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4164. /**
  4165. * Returns `true` if any components of `x` are `true`.
  4166. *
  4167. * @tsl
  4168. * @function
  4169. * @param {Node | number} x - The parameter.
  4170. * @returns {Node<bool>}
  4171. */
  4172. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4173. /**
  4174. * Converts a quantity in degrees to radians.
  4175. *
  4176. * @tsl
  4177. * @function
  4178. * @param {Node | number} x - The input in degrees.
  4179. * @returns {Node}
  4180. */
  4181. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4182. /**
  4183. * Convert a quantity in radians to degrees.
  4184. *
  4185. * @tsl
  4186. * @function
  4187. * @param {Node | number} x - The input in radians.
  4188. * @returns {Node}
  4189. */
  4190. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4191. /**
  4192. * Returns the natural exponentiation of the parameter.
  4193. *
  4194. * @tsl
  4195. * @function
  4196. * @param {Node | number} x - The parameter.
  4197. * @returns {Node}
  4198. */
  4199. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4200. /**
  4201. * Returns 2 raised to the power of the parameter.
  4202. *
  4203. * @tsl
  4204. * @function
  4205. * @param {Node | number} x - The parameter.
  4206. * @returns {Node}
  4207. */
  4208. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4209. /**
  4210. * Returns the natural logarithm of the parameter.
  4211. *
  4212. * @tsl
  4213. * @function
  4214. * @param {Node | number} x - The parameter.
  4215. * @returns {Node}
  4216. */
  4217. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4218. /**
  4219. * Returns the base 2 logarithm of the parameter.
  4220. *
  4221. * @tsl
  4222. * @function
  4223. * @param {Node | number} x - The parameter.
  4224. * @returns {Node}
  4225. */
  4226. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4227. /**
  4228. * Returns the square root of the parameter.
  4229. *
  4230. * @tsl
  4231. * @function
  4232. * @param {Node | number} x - The parameter.
  4233. * @returns {Node}
  4234. */
  4235. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4236. /**
  4237. * Returns the inverse of the square root of the parameter.
  4238. *
  4239. * @tsl
  4240. * @function
  4241. * @param {Node | number} x - The parameter.
  4242. * @returns {Node}
  4243. */
  4244. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4245. /**
  4246. * Finds the nearest integer less than or equal to the parameter.
  4247. *
  4248. * @tsl
  4249. * @function
  4250. * @param {Node | number} x - The parameter.
  4251. * @returns {Node}
  4252. */
  4253. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4254. /**
  4255. * Finds the nearest integer that is greater than or equal to the parameter.
  4256. *
  4257. * @tsl
  4258. * @function
  4259. * @param {Node | number} x - The parameter.
  4260. * @returns {Node}
  4261. */
  4262. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4263. /**
  4264. * Calculates the unit vector in the same direction as the original vector.
  4265. *
  4266. * @tsl
  4267. * @function
  4268. * @param {Node} x - The input vector.
  4269. * @returns {Node}
  4270. */
  4271. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4272. /**
  4273. * Computes the fractional part of the parameter.
  4274. *
  4275. * @tsl
  4276. * @function
  4277. * @param {Node | number} x - The parameter.
  4278. * @returns {Node}
  4279. */
  4280. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4281. /**
  4282. * Returns the sine of the parameter.
  4283. *
  4284. * @tsl
  4285. * @function
  4286. * @param {Node | number} x - The parameter.
  4287. * @returns {Node}
  4288. */
  4289. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4290. /**
  4291. * Returns the cosine of the parameter.
  4292. *
  4293. * @tsl
  4294. * @function
  4295. * @param {Node | number} x - The parameter.
  4296. * @returns {Node}
  4297. */
  4298. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS ).setParameterLength( 1 );
  4299. /**
  4300. * Returns the tangent of the parameter.
  4301. *
  4302. * @tsl
  4303. * @function
  4304. * @param {Node | number} x - The parameter.
  4305. * @returns {Node}
  4306. */
  4307. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4308. /**
  4309. * Returns the arcsine of the parameter.
  4310. *
  4311. * @tsl
  4312. * @function
  4313. * @param {Node | number} x - The parameter.
  4314. * @returns {Node}
  4315. */
  4316. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4317. /**
  4318. * Returns the arccosine of the parameter.
  4319. *
  4320. * @tsl
  4321. * @function
  4322. * @param {Node | number} x - The parameter.
  4323. * @returns {Node}
  4324. */
  4325. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4326. /**
  4327. * Returns the arc-tangent of the parameter.
  4328. * If two parameters are provided, the result is `atan2(y/x)`.
  4329. *
  4330. * @tsl
  4331. * @function
  4332. * @param {Node | number} y - The y parameter.
  4333. * @param {?(Node | number)} x - The x parameter.
  4334. * @returns {Node}
  4335. */
  4336. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4337. /**
  4338. * Returns the absolute value of the parameter.
  4339. *
  4340. * @tsl
  4341. * @function
  4342. * @param {Node | number} x - The parameter.
  4343. * @returns {Node}
  4344. */
  4345. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4346. /**
  4347. * Extracts the sign of the parameter.
  4348. *
  4349. * @tsl
  4350. * @function
  4351. * @param {Node | number} x - The parameter.
  4352. * @returns {Node}
  4353. */
  4354. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4355. /**
  4356. * Calculates the length of a vector.
  4357. *
  4358. * @tsl
  4359. * @function
  4360. * @param {Node} x - The parameter.
  4361. * @returns {Node<float>}
  4362. */
  4363. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4364. /**
  4365. * Negates the value of the parameter (-x).
  4366. *
  4367. * @tsl
  4368. * @function
  4369. * @param {Node | number} x - The parameter.
  4370. * @returns {Node}
  4371. */
  4372. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4373. /**
  4374. * Return `1` minus the parameter.
  4375. *
  4376. * @tsl
  4377. * @function
  4378. * @param {Node | number} x - The parameter.
  4379. * @returns {Node}
  4380. */
  4381. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4382. /**
  4383. * Returns the partial derivative of the parameter with respect to x.
  4384. *
  4385. * @tsl
  4386. * @function
  4387. * @param {Node | number} x - The parameter.
  4388. * @returns {Node}
  4389. */
  4390. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4391. /**
  4392. * Returns the partial derivative of the parameter with respect to y.
  4393. *
  4394. * @tsl
  4395. * @function
  4396. * @param {Node | number} x - The parameter.
  4397. * @returns {Node}
  4398. */
  4399. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4400. /**
  4401. * Rounds the parameter to the nearest integer.
  4402. *
  4403. * @tsl
  4404. * @function
  4405. * @param {Node | number} x - The parameter.
  4406. * @returns {Node}
  4407. */
  4408. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4409. /**
  4410. * Returns the reciprocal of the parameter `(1/x)`.
  4411. *
  4412. * @tsl
  4413. * @function
  4414. * @param {Node | number} x - The parameter.
  4415. * @returns {Node}
  4416. */
  4417. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4418. /**
  4419. * Truncates the parameter, removing the fractional part.
  4420. *
  4421. * @tsl
  4422. * @function
  4423. * @param {Node | number} x - The parameter.
  4424. * @returns {Node}
  4425. */
  4426. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4427. /**
  4428. * Returns the sum of the absolute derivatives in x and y.
  4429. *
  4430. * @tsl
  4431. * @function
  4432. * @param {Node | number} x - The parameter.
  4433. * @returns {Node}
  4434. */
  4435. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4436. /**
  4437. * Returns the transpose of a matrix.
  4438. *
  4439. * @tsl
  4440. * @function
  4441. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4442. * @returns {Node}
  4443. */
  4444. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4445. // 2 inputs
  4446. /**
  4447. * Reinterpret the bit representation of a value in one type as a value in another type.
  4448. *
  4449. * @tsl
  4450. * @function
  4451. * @param {Node | number} x - The parameter.
  4452. * @param {string} y - The new type.
  4453. * @returns {Node}
  4454. */
  4455. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4456. /**
  4457. * Returns `true` if `x` equals `y`.
  4458. *
  4459. * @tsl
  4460. * @function
  4461. * @param {Node | number} x - The first parameter.
  4462. * @param {Node | number} y - The second parameter.
  4463. * @deprecated since r175. Use {@link equal} instead.
  4464. * @returns {Node<bool>}
  4465. */
  4466. const equals = ( x, y ) => { // @deprecated, r172
  4467. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4468. return equal( x, y );
  4469. };
  4470. /**
  4471. * Returns the least of the given values.
  4472. *
  4473. * @tsl
  4474. * @function
  4475. * @param {...(Node | number)} values - The values to compare.
  4476. * @returns {Node}
  4477. */
  4478. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4479. /**
  4480. * Returns the greatest of the given values.
  4481. *
  4482. * @tsl
  4483. * @function
  4484. * @param {...(Node | number)} values - The values to compare.
  4485. * @returns {Node}
  4486. */
  4487. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4488. /**
  4489. * Generate a step function by comparing two values.
  4490. *
  4491. * @tsl
  4492. * @function
  4493. * @param {Node | number} x - The y parameter.
  4494. * @param {Node | number} y - The x parameter.
  4495. * @returns {Node}
  4496. */
  4497. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4498. /**
  4499. * Calculates the reflection direction for an incident vector.
  4500. *
  4501. * @tsl
  4502. * @function
  4503. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4504. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4505. * @returns {Node<vec2|vec3|vec4>}
  4506. */
  4507. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4508. /**
  4509. * Calculates the distance between two points.
  4510. *
  4511. * @tsl
  4512. * @function
  4513. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4514. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4515. * @returns {Node<float>}
  4516. */
  4517. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4518. /**
  4519. * Calculates the absolute difference between two values.
  4520. *
  4521. * @tsl
  4522. * @function
  4523. * @param {Node | number} x - The first parameter.
  4524. * @param {Node | number} y - The second parameter.
  4525. * @returns {Node}
  4526. */
  4527. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4528. /**
  4529. * Calculates the dot product of two vectors.
  4530. *
  4531. * @tsl
  4532. * @function
  4533. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4534. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4535. * @returns {Node<float>}
  4536. */
  4537. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4538. /**
  4539. * Calculates the cross product of two vectors.
  4540. *
  4541. * @tsl
  4542. * @function
  4543. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4544. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4545. * @returns {Node<vec2|vec3|vec4>}
  4546. */
  4547. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4548. /**
  4549. * Return the value of the first parameter raised to the power of the second one.
  4550. *
  4551. * @tsl
  4552. * @function
  4553. * @param {Node | number} x - The first parameter.
  4554. * @param {Node | number} y - The second parameter.
  4555. * @returns {Node}
  4556. */
  4557. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW ).setParameterLength( 2 );
  4558. /**
  4559. * Returns the square of the parameter.
  4560. *
  4561. * @tsl
  4562. * @function
  4563. * @param {Node | number} x - The first parameter.
  4564. * @returns {Node}
  4565. */
  4566. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4567. /**
  4568. * Returns the cube of the parameter.
  4569. *
  4570. * @tsl
  4571. * @function
  4572. * @param {Node | number} x - The first parameter.
  4573. * @returns {Node}
  4574. */
  4575. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4576. /**
  4577. * Returns the fourth power of the parameter.
  4578. *
  4579. * @tsl
  4580. * @function
  4581. * @param {Node | number} x - The first parameter.
  4582. * @returns {Node}
  4583. */
  4584. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4585. /**
  4586. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4587. *
  4588. * @tsl
  4589. * @function
  4590. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4591. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4592. * @returns {Node}
  4593. */
  4594. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4595. /**
  4596. * Returns the cube root of a number.
  4597. *
  4598. * @tsl
  4599. * @function
  4600. * @param {Node | number} a - The first parameter.
  4601. * @returns {Node}
  4602. */
  4603. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4604. /**
  4605. * Calculate the squared length of a vector.
  4606. *
  4607. * @tsl
  4608. * @function
  4609. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4610. * @returns {Node<float>}
  4611. */
  4612. const lengthSq = ( a ) => dot( a, a );
  4613. /**
  4614. * Linearly interpolates between two values.
  4615. *
  4616. * @tsl
  4617. * @function
  4618. * @param {Node | number} a - The first parameter.
  4619. * @param {Node | number} b - The second parameter.
  4620. * @param {Node | number} t - The interpolation value.
  4621. * @returns {Node}
  4622. */
  4623. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4624. /**
  4625. * Constrains a value to lie between two further values.
  4626. *
  4627. * @tsl
  4628. * @function
  4629. * @param {Node | number} value - The value to constrain.
  4630. * @param {Node | number} [low=0] - The lower bound.
  4631. * @param {Node | number} [high=1] - The upper bound.
  4632. * @returns {Node}
  4633. */
  4634. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4635. /**
  4636. * Constrains a value between `0` and `1`.
  4637. *
  4638. * @tsl
  4639. * @function
  4640. * @param {Node | number} value - The value to constrain.
  4641. * @returns {Node}
  4642. */
  4643. const saturate = ( value ) => clamp( value );
  4644. /**
  4645. * Calculates the refraction direction for an incident vector.
  4646. *
  4647. * @tsl
  4648. * @function
  4649. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4650. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4651. * @param {Node<float>} eta - The ratio of indices of refraction.
  4652. * @returns {Node<vec2|vec3|vec4>}
  4653. */
  4654. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  4655. /**
  4656. * Performs a Hermite interpolation between two values.
  4657. *
  4658. * @tsl
  4659. * @function
  4660. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4661. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4662. * @param {Node | number} x - The source value for interpolation.
  4663. * @returns {Node}
  4664. */
  4665. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  4666. /**
  4667. * Returns a vector pointing in the same direction as another.
  4668. *
  4669. * @tsl
  4670. * @function
  4671. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4672. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4673. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4674. * @returns {Node<vec2|vec3|vec4>}
  4675. */
  4676. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  4677. /**
  4678. * Returns a random value for the given uv.
  4679. *
  4680. * @tsl
  4681. * @function
  4682. * @param {Node<vec2>} uv - The uv node.
  4683. * @returns {Node<float>}
  4684. */
  4685. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4686. const a = 12.9898, b = 78.233, c = 43758.5453;
  4687. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4688. return fract( sin( sn ).mul( c ) );
  4689. } );
  4690. /**
  4691. * Alias for `mix()` with a different parameter order.
  4692. *
  4693. * @tsl
  4694. * @function
  4695. * @param {Node | number} t - The interpolation value.
  4696. * @param {Node | number} e1 - The first parameter.
  4697. * @param {Node | number} e2 - The second parameter.
  4698. * @returns {Node}
  4699. */
  4700. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4701. /**
  4702. * Alias for `smoothstep()` with a different parameter order.
  4703. *
  4704. * @tsl
  4705. * @function
  4706. * @param {Node | number} x - The source value for interpolation.
  4707. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4708. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4709. * @returns {Node}
  4710. */
  4711. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4712. /**
  4713. * Returns the arc-tangent of the quotient of its parameters.
  4714. *
  4715. * @tsl
  4716. * @function
  4717. * @deprecated since r172. Use {@link atan} instead.
  4718. *
  4719. * @param {Node | number} y - The y parameter.
  4720. * @param {Node | number} x - The x parameter.
  4721. * @returns {Node}
  4722. */
  4723. const atan2 = ( y, x ) => { // @deprecated, r172
  4724. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4725. return atan( y, x );
  4726. };
  4727. // GLSL alias function
  4728. const faceforward = faceForward;
  4729. const inversesqrt = inverseSqrt;
  4730. // Method chaining
  4731. addMethodChaining( 'all', all );
  4732. addMethodChaining( 'any', any );
  4733. addMethodChaining( 'equals', equals );
  4734. addMethodChaining( 'radians', radians );
  4735. addMethodChaining( 'degrees', degrees );
  4736. addMethodChaining( 'exp', exp );
  4737. addMethodChaining( 'exp2', exp2 );
  4738. addMethodChaining( 'log', log );
  4739. addMethodChaining( 'log2', log2 );
  4740. addMethodChaining( 'sqrt', sqrt );
  4741. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4742. addMethodChaining( 'floor', floor );
  4743. addMethodChaining( 'ceil', ceil );
  4744. addMethodChaining( 'normalize', normalize );
  4745. addMethodChaining( 'fract', fract );
  4746. addMethodChaining( 'sin', sin );
  4747. addMethodChaining( 'cos', cos );
  4748. addMethodChaining( 'tan', tan );
  4749. addMethodChaining( 'asin', asin );
  4750. addMethodChaining( 'acos', acos );
  4751. addMethodChaining( 'atan', atan );
  4752. addMethodChaining( 'abs', abs );
  4753. addMethodChaining( 'sign', sign );
  4754. addMethodChaining( 'length', length );
  4755. addMethodChaining( 'lengthSq', lengthSq );
  4756. addMethodChaining( 'negate', negate );
  4757. addMethodChaining( 'oneMinus', oneMinus );
  4758. addMethodChaining( 'dFdx', dFdx );
  4759. addMethodChaining( 'dFdy', dFdy );
  4760. addMethodChaining( 'round', round );
  4761. addMethodChaining( 'reciprocal', reciprocal );
  4762. addMethodChaining( 'trunc', trunc );
  4763. addMethodChaining( 'fwidth', fwidth );
  4764. addMethodChaining( 'atan2', atan2 );
  4765. addMethodChaining( 'min', min$1 );
  4766. addMethodChaining( 'max', max$1 );
  4767. addMethodChaining( 'step', step );
  4768. addMethodChaining( 'reflect', reflect );
  4769. addMethodChaining( 'distance', distance );
  4770. addMethodChaining( 'dot', dot );
  4771. addMethodChaining( 'cross', cross );
  4772. addMethodChaining( 'pow', pow );
  4773. addMethodChaining( 'pow2', pow2 );
  4774. addMethodChaining( 'pow3', pow3 );
  4775. addMethodChaining( 'pow4', pow4 );
  4776. addMethodChaining( 'transformDirection', transformDirection );
  4777. addMethodChaining( 'mix', mixElement );
  4778. addMethodChaining( 'clamp', clamp );
  4779. addMethodChaining( 'refract', refract );
  4780. addMethodChaining( 'smoothstep', smoothstepElement );
  4781. addMethodChaining( 'faceForward', faceForward );
  4782. addMethodChaining( 'difference', difference );
  4783. addMethodChaining( 'saturate', saturate );
  4784. addMethodChaining( 'cbrt', cbrt );
  4785. addMethodChaining( 'transpose', transpose );
  4786. addMethodChaining( 'rand', rand );
  4787. /**
  4788. * Represents a logical `if/else` statement. Can be used as an alternative
  4789. * to the `If()`/`Else()` syntax.
  4790. *
  4791. * The corresponding TSL `select()` looks like so:
  4792. * ```js
  4793. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4794. * ```
  4795. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4796. * determine the outcome of the entire statement.
  4797. *
  4798. * @augments Node
  4799. */
  4800. class ConditionalNode extends Node {
  4801. static get type() {
  4802. return 'ConditionalNode';
  4803. }
  4804. /**
  4805. * Constructs a new conditional node.
  4806. *
  4807. * @param {Node} condNode - The node that defines the condition.
  4808. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4809. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4810. */
  4811. constructor( condNode, ifNode, elseNode = null ) {
  4812. super();
  4813. /**
  4814. * The node that defines the condition.
  4815. *
  4816. * @type {Node}
  4817. */
  4818. this.condNode = condNode;
  4819. /**
  4820. * The node that is evaluate when the condition ends up `true`.
  4821. *
  4822. * @type {Node}
  4823. */
  4824. this.ifNode = ifNode;
  4825. /**
  4826. * The node that is evaluate when the condition ends up `false`.
  4827. *
  4828. * @type {?Node}
  4829. * @default null
  4830. */
  4831. this.elseNode = elseNode;
  4832. }
  4833. /**
  4834. * This method is overwritten since the node type is inferred from the if/else
  4835. * nodes.
  4836. *
  4837. * @param {NodeBuilder} builder - The current node builder.
  4838. * @return {string} The node type.
  4839. */
  4840. getNodeType( builder ) {
  4841. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4842. if ( ifNode === undefined ) {
  4843. // fallback setup
  4844. this.setup( builder );
  4845. return this.getNodeType( builder );
  4846. }
  4847. const ifType = ifNode.getNodeType( builder );
  4848. if ( elseNode !== null ) {
  4849. const elseType = elseNode.getNodeType( builder );
  4850. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4851. return elseType;
  4852. }
  4853. }
  4854. return ifType;
  4855. }
  4856. setup( builder ) {
  4857. const condNode = this.condNode.cache();
  4858. const ifNode = this.ifNode.cache();
  4859. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4860. //
  4861. const currentNodeBlock = builder.context.nodeBlock;
  4862. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4863. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4864. //
  4865. const properties = builder.getNodeProperties( this );
  4866. properties.condNode = condNode;
  4867. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4868. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4869. }
  4870. generate( builder, output ) {
  4871. const type = this.getNodeType( builder );
  4872. const nodeData = builder.getDataFromNode( this );
  4873. if ( nodeData.nodeProperty !== undefined ) {
  4874. return nodeData.nodeProperty;
  4875. }
  4876. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4877. const functionNode = builder.currentFunctionNode;
  4878. const needsOutput = output !== 'void';
  4879. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4880. nodeData.nodeProperty = nodeProperty;
  4881. const nodeSnippet = condNode.build( builder, 'bool' );
  4882. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4883. let ifSnippet = ifNode.build( builder, type );
  4884. if ( ifSnippet ) {
  4885. if ( needsOutput ) {
  4886. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4887. } else {
  4888. ifSnippet = 'return ' + ifSnippet + ';';
  4889. if ( functionNode === null ) {
  4890. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  4891. ifSnippet = '// ' + ifSnippet;
  4892. }
  4893. }
  4894. }
  4895. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4896. if ( elseNode !== null ) {
  4897. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4898. let elseSnippet = elseNode.build( builder, type );
  4899. if ( elseSnippet ) {
  4900. if ( needsOutput ) {
  4901. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4902. } else {
  4903. elseSnippet = 'return ' + elseSnippet + ';';
  4904. if ( functionNode === null ) {
  4905. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  4906. elseSnippet = '// ' + elseSnippet;
  4907. }
  4908. }
  4909. }
  4910. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4911. } else {
  4912. builder.addFlowCode( '\n\n' );
  4913. }
  4914. return builder.format( nodeProperty, type, output );
  4915. }
  4916. }
  4917. /**
  4918. * TSL function for creating a conditional node.
  4919. *
  4920. * @tsl
  4921. * @function
  4922. * @param {Node} condNode - The node that defines the condition.
  4923. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4924. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4925. * @returns {ConditionalNode}
  4926. */
  4927. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  4928. addMethodChaining( 'select', select );
  4929. // Deprecated
  4930. /**
  4931. * @tsl
  4932. * @function
  4933. * @deprecated since r168. Use {@link select} instead.
  4934. *
  4935. * @param {...any} params
  4936. * @returns {ConditionalNode}
  4937. */
  4938. const cond = ( ...params ) => { // @deprecated, r168
  4939. console.warn( 'THREE.TSL: cond() has been renamed to select().' );
  4940. return select( ...params );
  4941. };
  4942. addMethodChaining( 'cond', cond );
  4943. /**
  4944. * This node can be used as a context management component for another node.
  4945. * {@link NodeBuilder} performs its node building process in a specific context and
  4946. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4947. *
  4948. * ```js
  4949. *node.context( { getUV: () => customCoord } );
  4950. *```
  4951. * @augments Node
  4952. */
  4953. class ContextNode extends Node {
  4954. static get type() {
  4955. return 'ContextNode';
  4956. }
  4957. /**
  4958. * Constructs a new context node.
  4959. *
  4960. * @param {Node} node - The node whose context should be modified.
  4961. * @param {Object} [value={}] - The modified context data.
  4962. */
  4963. constructor( node, value = {} ) {
  4964. super();
  4965. /**
  4966. * This flag can be used for type testing.
  4967. *
  4968. * @type {boolean}
  4969. * @readonly
  4970. * @default true
  4971. */
  4972. this.isContextNode = true;
  4973. /**
  4974. * The node whose context should be modified.
  4975. *
  4976. * @type {Node}
  4977. */
  4978. this.node = node;
  4979. /**
  4980. * The modified context data.
  4981. *
  4982. * @type {Object}
  4983. * @default {}
  4984. */
  4985. this.value = value;
  4986. }
  4987. /**
  4988. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  4989. *
  4990. * @return {Node} A reference to {@link ContextNode#node}.
  4991. */
  4992. getScope() {
  4993. return this.node.getScope();
  4994. }
  4995. /**
  4996. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  4997. *
  4998. * @param {NodeBuilder} builder - The current node builder.
  4999. * @return {string} The node type.
  5000. */
  5001. getNodeType( builder ) {
  5002. return this.node.getNodeType( builder );
  5003. }
  5004. analyze( builder ) {
  5005. this.node.build( builder );
  5006. }
  5007. setup( builder ) {
  5008. const previousContext = builder.getContext();
  5009. builder.setContext( { ...builder.context, ...this.value } );
  5010. const node = this.node.build( builder );
  5011. builder.setContext( previousContext );
  5012. return node;
  5013. }
  5014. generate( builder, output ) {
  5015. const previousContext = builder.getContext();
  5016. builder.setContext( { ...builder.context, ...this.value } );
  5017. const snippet = this.node.build( builder, output );
  5018. builder.setContext( previousContext );
  5019. return snippet;
  5020. }
  5021. }
  5022. /**
  5023. * TSL function for creating a context node.
  5024. *
  5025. * @tsl
  5026. * @function
  5027. * @param {Node} node - The node whose context should be modified.
  5028. * @param {Object} [value={}] - The modified context data.
  5029. * @returns {ContextNode}
  5030. */
  5031. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5032. /**
  5033. * TSL function for defining a label context value for a given node.
  5034. *
  5035. * @tsl
  5036. * @function
  5037. * @param {Node} node - The node whose context should be modified.
  5038. * @param {string} name - The name/label to set.
  5039. * @returns {ContextNode}
  5040. */
  5041. const label = ( node, name ) => context( node, { label: name } );
  5042. addMethodChaining( 'context', context );
  5043. addMethodChaining( 'label', label );
  5044. /**
  5045. * Class for representing shader variables as nodes. Variables are created from
  5046. * existing nodes like the following:
  5047. *
  5048. * ```js
  5049. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5050. * ```
  5051. *
  5052. * @augments Node
  5053. */
  5054. class VarNode extends Node {
  5055. static get type() {
  5056. return 'VarNode';
  5057. }
  5058. /**
  5059. * Constructs a new variable node.
  5060. *
  5061. * @param {Node} node - The node for which a variable should be created.
  5062. * @param {?string} [name=null] - The name of the variable in the shader.
  5063. * @param {boolean} [readOnly=false] - The read-only flag.
  5064. */
  5065. constructor( node, name = null, readOnly = false ) {
  5066. super();
  5067. /**
  5068. * The node for which a variable should be created.
  5069. *
  5070. * @type {Node}
  5071. */
  5072. this.node = node;
  5073. /**
  5074. * The name of the variable in the shader. If no name is defined,
  5075. * the node system auto-generates one.
  5076. *
  5077. * @type {?string}
  5078. * @default null
  5079. */
  5080. this.name = name;
  5081. /**
  5082. * `VarNode` sets this property to `true` by default.
  5083. *
  5084. * @type {boolean}
  5085. * @default true
  5086. */
  5087. this.global = true;
  5088. /**
  5089. * This flag can be used for type testing.
  5090. *
  5091. * @type {boolean}
  5092. * @readonly
  5093. * @default true
  5094. */
  5095. this.isVarNode = true;
  5096. /**
  5097. *
  5098. * The read-only flag.
  5099. *
  5100. * @type {boolean}
  5101. * @default false
  5102. */
  5103. this.readOnly = readOnly;
  5104. }
  5105. getMemberType( builder, name ) {
  5106. return this.node.getMemberType( builder, name );
  5107. }
  5108. getElementType( builder ) {
  5109. return this.node.getElementType( builder );
  5110. }
  5111. getNodeType( builder ) {
  5112. return this.node.getNodeType( builder );
  5113. }
  5114. generate( builder ) {
  5115. const { node, name, readOnly } = this;
  5116. const { renderer } = builder;
  5117. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5118. let isDeterministic = false;
  5119. let shouldTreatAsReadOnly = false;
  5120. if ( readOnly ) {
  5121. isDeterministic = builder.isDeterministic( node );
  5122. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5123. }
  5124. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5125. const snippet = node.build( builder, vectorType );
  5126. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5127. const propertyName = builder.getPropertyName( nodeVar );
  5128. let declarationPrefix = propertyName;
  5129. if ( shouldTreatAsReadOnly ) {
  5130. if ( isWebGPUBackend ) {
  5131. declarationPrefix = isDeterministic
  5132. ? `const ${ propertyName }`
  5133. : `let ${ propertyName }`;
  5134. } else {
  5135. const count = builder.getArrayCount( node );
  5136. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5137. }
  5138. }
  5139. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5140. return propertyName;
  5141. }
  5142. }
  5143. /**
  5144. * TSL function for creating a var node.
  5145. *
  5146. * @tsl
  5147. * @function
  5148. * @param {Node} node - The node for which a variable should be created.
  5149. * @param {?string} name - The name of the variable in the shader.
  5150. * @returns {VarNode}
  5151. */
  5152. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5153. /**
  5154. * TSL function for creating a var node.
  5155. *
  5156. * @tsl
  5157. * @function
  5158. * @param {Node} node - The node for which a variable should be created.
  5159. * @param {?string} name - The name of the variable in the shader.
  5160. * @returns {VarNode}
  5161. */
  5162. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5163. /**
  5164. * TSL function for creating a const node.
  5165. *
  5166. * @tsl
  5167. * @function
  5168. * @param {Node} node - The node for which a constant should be created.
  5169. * @param {?string} name - The name of the constant in the shader.
  5170. * @returns {VarNode}
  5171. */
  5172. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5173. // Method chaining
  5174. addMethodChaining( 'toVar', Var );
  5175. addMethodChaining( 'toConst', Const );
  5176. // Deprecated
  5177. /**
  5178. * @tsl
  5179. * @function
  5180. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  5181. *
  5182. * @param {any} node
  5183. * @returns {VarNode}
  5184. */
  5185. const temp = ( node ) => { // @deprecated, r170
  5186. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  5187. return createVar( node );
  5188. };
  5189. addMethodChaining( 'temp', temp );
  5190. /**
  5191. * Class for representing shader varyings as nodes. Varyings are create from
  5192. * existing nodes like the following:
  5193. *
  5194. * ```js
  5195. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5196. * ```
  5197. *
  5198. * @augments Node
  5199. */
  5200. class VaryingNode extends Node {
  5201. static get type() {
  5202. return 'VaryingNode';
  5203. }
  5204. /**
  5205. * Constructs a new varying node.
  5206. *
  5207. * @param {Node} node - The node for which a varying should be created.
  5208. * @param {?string} name - The name of the varying in the shader.
  5209. */
  5210. constructor( node, name = null ) {
  5211. super();
  5212. /**
  5213. * The node for which a varying should be created.
  5214. *
  5215. * @type {Node}
  5216. */
  5217. this.node = node;
  5218. /**
  5219. * The name of the varying in the shader. If no name is defined,
  5220. * the node system auto-generates one.
  5221. *
  5222. * @type {?string}
  5223. * @default null
  5224. */
  5225. this.name = name;
  5226. /**
  5227. * This flag can be used for type testing.
  5228. *
  5229. * @type {boolean}
  5230. * @readonly
  5231. * @default true
  5232. */
  5233. this.isVaryingNode = true;
  5234. /**
  5235. * The interpolation type of the varying data.
  5236. *
  5237. * @type {?string}
  5238. * @default null
  5239. */
  5240. this.interpolationType = null;
  5241. /**
  5242. * The interpolation sampling type of varying data.
  5243. *
  5244. * @type {?string}
  5245. * @default null
  5246. */
  5247. this.interpolationSampling = null;
  5248. }
  5249. /**
  5250. * The method is overwritten so it always returns `true`.
  5251. *
  5252. * @param {NodeBuilder} builder - The current node builder.
  5253. * @return {boolean} Whether this node is global or not.
  5254. */
  5255. isGlobal( /*builder*/ ) {
  5256. return true;
  5257. }
  5258. /**
  5259. * Defines the interpolation type of the varying.
  5260. *
  5261. * @param {string} type - The interpolation type.
  5262. * @param {?string} sampling - The interpolation sampling type
  5263. * @return {VaryingNode} A reference to this node.
  5264. */
  5265. setInterpolation( type, sampling = null ) {
  5266. this.interpolationType = type;
  5267. this.interpolationSampling = sampling;
  5268. return this;
  5269. }
  5270. getHash( builder ) {
  5271. return this.name || super.getHash( builder );
  5272. }
  5273. getNodeType( builder ) {
  5274. // VaryingNode is auto type
  5275. return this.node.getNodeType( builder );
  5276. }
  5277. /**
  5278. * This method performs the setup of a varying node with the current node builder.
  5279. *
  5280. * @param {NodeBuilder} builder - The current node builder.
  5281. * @return {NodeVarying} The node varying from the node builder.
  5282. */
  5283. setupVarying( builder ) {
  5284. const properties = builder.getNodeProperties( this );
  5285. let varying = properties.varying;
  5286. if ( varying === undefined ) {
  5287. const name = this.name;
  5288. const type = this.getNodeType( builder );
  5289. const interpolationType = this.interpolationType;
  5290. const interpolationSampling = this.interpolationSampling;
  5291. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5292. properties.node = this.node;
  5293. }
  5294. // this property can be used to check if the varying can be optimized for a variable
  5295. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5296. return varying;
  5297. }
  5298. setup( builder ) {
  5299. this.setupVarying( builder );
  5300. }
  5301. analyze( builder ) {
  5302. this.setupVarying( builder );
  5303. return this.node.analyze( builder );
  5304. }
  5305. generate( builder ) {
  5306. const properties = builder.getNodeProperties( this );
  5307. const varying = this.setupVarying( builder );
  5308. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  5309. if ( properties.propertyName === undefined || needsReassign ) {
  5310. const type = this.getNodeType( builder );
  5311. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5312. // force node run in vertex stage
  5313. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5314. properties.propertyName = propertyName;
  5315. if ( needsReassign ) {
  5316. // once reassign varying in fragment stage
  5317. properties.reassignPosition = false;
  5318. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  5319. properties.reassignPosition = true;
  5320. }
  5321. }
  5322. return builder.getPropertyName( varying );
  5323. }
  5324. }
  5325. /**
  5326. * TSL function for creating a varying node.
  5327. *
  5328. * @tsl
  5329. * @function
  5330. * @param {Node} node - The node for which a varying should be created.
  5331. * @param {?string} name - The name of the varying in the shader.
  5332. * @returns {VaryingNode}
  5333. */
  5334. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5335. /**
  5336. * Computes a node in the vertex stage.
  5337. *
  5338. * @tsl
  5339. * @function
  5340. * @param {Node} node - The node which should be executed in the vertex stage.
  5341. * @returns {VaryingNode}
  5342. */
  5343. const vertexStage = ( node ) => varying( node );
  5344. addMethodChaining( 'toVarying', varying );
  5345. addMethodChaining( 'toVertexStage', vertexStage );
  5346. // Deprecated
  5347. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5348. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5349. return varying( ...params );
  5350. } );
  5351. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5352. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5353. return varying( ...params );
  5354. } );
  5355. /**
  5356. * Converts the given color value from sRGB to linear-sRGB color space.
  5357. *
  5358. * @tsl
  5359. * @function
  5360. * @param {Node<vec3>} color - The sRGB color.
  5361. * @return {Node<vec3>} The linear-sRGB color.
  5362. */
  5363. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5364. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5365. const b = color.mul( 0.0773993808 );
  5366. const factor = color.lessThanEqual( 0.04045 );
  5367. const rgbResult = mix( a, b, factor );
  5368. return rgbResult;
  5369. } ).setLayout( {
  5370. name: 'sRGBTransferEOTF',
  5371. type: 'vec3',
  5372. inputs: [
  5373. { name: 'color', type: 'vec3' }
  5374. ]
  5375. } );
  5376. /**
  5377. * Converts the given color value from linear-sRGB to sRGB color space.
  5378. *
  5379. * @tsl
  5380. * @function
  5381. * @param {Node<vec3>} color - The linear-sRGB color.
  5382. * @return {Node<vec3>} The sRGB color.
  5383. */
  5384. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5385. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5386. const b = color.mul( 12.92 );
  5387. const factor = color.lessThanEqual( 0.0031308 );
  5388. const rgbResult = mix( a, b, factor );
  5389. return rgbResult;
  5390. } ).setLayout( {
  5391. name: 'sRGBTransferOETF',
  5392. type: 'vec3',
  5393. inputs: [
  5394. { name: 'color', type: 'vec3' }
  5395. ]
  5396. } );
  5397. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5398. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5399. /**
  5400. * This node represents a color space conversion. Meaning it converts
  5401. * a color value from a source to a target color space.
  5402. *
  5403. * @augments TempNode
  5404. */
  5405. class ColorSpaceNode extends TempNode {
  5406. static get type() {
  5407. return 'ColorSpaceNode';
  5408. }
  5409. /**
  5410. * Constructs a new color space node.
  5411. *
  5412. * @param {Node} colorNode - Represents the color to convert.
  5413. * @param {string} source - The source color space.
  5414. * @param {string} target - The target color space.
  5415. */
  5416. constructor( colorNode, source, target ) {
  5417. super( 'vec4' );
  5418. /**
  5419. * Represents the color to convert.
  5420. *
  5421. * @type {Node}
  5422. */
  5423. this.colorNode = colorNode;
  5424. /**
  5425. * The source color space.
  5426. *
  5427. * @type {string}
  5428. */
  5429. this.source = source;
  5430. /**
  5431. * The target color space.
  5432. *
  5433. * @type {string}
  5434. */
  5435. this.target = target;
  5436. }
  5437. /**
  5438. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5439. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5440. * color management and renderer.
  5441. *
  5442. * @param {NodeBuilder} builder - The current node builder.
  5443. * @param {string} colorSpace - The color space to resolve.
  5444. * @return {string} The resolved color space.
  5445. */
  5446. resolveColorSpace( builder, colorSpace ) {
  5447. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5448. return ColorManagement.workingColorSpace;
  5449. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5450. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5451. }
  5452. return colorSpace;
  5453. }
  5454. setup( builder ) {
  5455. const { colorNode } = this;
  5456. const source = this.resolveColorSpace( builder, this.source );
  5457. const target = this.resolveColorSpace( builder, this.target );
  5458. let outputNode = colorNode;
  5459. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5460. return outputNode;
  5461. }
  5462. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5463. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5464. }
  5465. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5466. outputNode = vec4(
  5467. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5468. outputNode.a
  5469. );
  5470. }
  5471. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5472. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5473. }
  5474. return outputNode;
  5475. }
  5476. }
  5477. /**
  5478. * TSL function for converting a given color node to the current output color space.
  5479. *
  5480. * @tsl
  5481. * @function
  5482. * @param {Node} node - Represents the node to convert.
  5483. * @returns {ColorSpaceNode}
  5484. */
  5485. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  5486. /**
  5487. * TSL function for converting a given color node to the current working color space.
  5488. *
  5489. * @tsl
  5490. * @function
  5491. * @param {Node} node - Represents the node to convert.
  5492. * @returns {ColorSpaceNode}
  5493. */
  5494. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  5495. /**
  5496. * TSL function for converting a given color node from the current working color space to the given color space.
  5497. *
  5498. * @tsl
  5499. * @function
  5500. * @param {Node} node - Represents the node to convert.
  5501. * @param {string} colorSpace - The target color space.
  5502. * @returns {ColorSpaceNode}
  5503. */
  5504. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  5505. /**
  5506. * TSL function for converting a given color node from the given color space to the current working color space.
  5507. *
  5508. * @tsl
  5509. * @function
  5510. * @param {Node} node - Represents the node to convert.
  5511. * @param {string} colorSpace - The source color space.
  5512. * @returns {ColorSpaceNode}
  5513. */
  5514. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  5515. /**
  5516. * TSL function for converting a given color node from one color space to another one.
  5517. *
  5518. * @tsl
  5519. * @function
  5520. * @param {Node} node - Represents the node to convert.
  5521. * @param {string} sourceColorSpace - The source color space.
  5522. * @param {string} targetColorSpace - The target color space.
  5523. * @returns {ColorSpaceNode}
  5524. */
  5525. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5526. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  5527. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  5528. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5529. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5530. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5531. /**
  5532. * This class is only relevant if the referenced property is array-like.
  5533. * In this case, `ReferenceElementNode` allows to refer to a specific
  5534. * element inside the data structure via an index.
  5535. *
  5536. * @augments ArrayElementNode
  5537. */
  5538. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5539. static get type() {
  5540. return 'ReferenceElementNode';
  5541. }
  5542. /**
  5543. * Constructs a new reference element node.
  5544. *
  5545. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5546. * @param {Node} indexNode - The index node that defines the element access.
  5547. */
  5548. constructor( referenceNode, indexNode ) {
  5549. super( referenceNode, indexNode );
  5550. /**
  5551. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5552. * property references to the current node.
  5553. *
  5554. * @type {?ReferenceBaseNode}
  5555. * @default null
  5556. */
  5557. this.referenceNode = referenceNode;
  5558. /**
  5559. * This flag can be used for type testing.
  5560. *
  5561. * @type {boolean}
  5562. * @readonly
  5563. * @default true
  5564. */
  5565. this.isReferenceElementNode = true;
  5566. }
  5567. /**
  5568. * This method is overwritten since the node type is inferred from
  5569. * the uniform type of the reference node.
  5570. *
  5571. * @return {string} The node type.
  5572. */
  5573. getNodeType() {
  5574. return this.referenceNode.uniformType;
  5575. }
  5576. generate( builder ) {
  5577. const snippet = super.generate( builder );
  5578. const arrayType = this.referenceNode.getNodeType();
  5579. const elementType = this.getNodeType();
  5580. return builder.format( snippet, arrayType, elementType );
  5581. }
  5582. };
  5583. /**
  5584. * Base class for nodes which establishes a reference to a property of another object.
  5585. * In this way, the value of the node is automatically linked to the value of
  5586. * referenced object. Reference nodes internally represent the linked value
  5587. * as a uniform.
  5588. *
  5589. * @augments Node
  5590. */
  5591. class ReferenceBaseNode extends Node {
  5592. static get type() {
  5593. return 'ReferenceBaseNode';
  5594. }
  5595. /**
  5596. * Constructs a new reference base node.
  5597. *
  5598. * @param {string} property - The name of the property the node refers to.
  5599. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5600. * @param {?Object} [object=null] - The object the property belongs to.
  5601. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5602. */
  5603. constructor( property, uniformType, object = null, count = null ) {
  5604. super();
  5605. /**
  5606. * The name of the property the node refers to.
  5607. *
  5608. * @type {string}
  5609. */
  5610. this.property = property;
  5611. /**
  5612. * The uniform type that should be used to represent the property value.
  5613. *
  5614. * @type {string}
  5615. */
  5616. this.uniformType = uniformType;
  5617. /**
  5618. * The object the property belongs to.
  5619. *
  5620. * @type {?Object}
  5621. * @default null
  5622. */
  5623. this.object = object;
  5624. /**
  5625. * When the linked property is an array, this parameter defines its length.
  5626. *
  5627. * @type {?number}
  5628. * @default null
  5629. */
  5630. this.count = count;
  5631. /**
  5632. * The property name might have dots so nested properties can be referred.
  5633. * The hierarchy of the names is stored inside this array.
  5634. *
  5635. * @type {Array<string>}
  5636. */
  5637. this.properties = property.split( '.' );
  5638. /**
  5639. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5640. * since the final reference might be updated from calling code.
  5641. *
  5642. * @type {?Object}
  5643. * @default null
  5644. */
  5645. this.reference = object;
  5646. /**
  5647. * The uniform node that holds the value of the reference node.
  5648. *
  5649. * @type {UniformNode}
  5650. * @default null
  5651. */
  5652. this.node = null;
  5653. /**
  5654. * The uniform group of the internal uniform.
  5655. *
  5656. * @type {UniformGroupNode}
  5657. * @default null
  5658. */
  5659. this.group = null;
  5660. /**
  5661. * Overwritten since reference nodes are updated per object.
  5662. *
  5663. * @type {string}
  5664. * @default 'object'
  5665. */
  5666. this.updateType = NodeUpdateType.OBJECT;
  5667. }
  5668. /**
  5669. * Sets the uniform group for this reference node.
  5670. *
  5671. * @param {UniformGroupNode} group - The uniform group to set.
  5672. * @return {ReferenceBaseNode} A reference to this node.
  5673. */
  5674. setGroup( group ) {
  5675. this.group = group;
  5676. return this;
  5677. }
  5678. /**
  5679. * When the referred property is array-like, this method can be used
  5680. * to access elements via an index node.
  5681. *
  5682. * @param {IndexNode} indexNode - indexNode.
  5683. * @return {ReferenceElementNode} A reference to an element.
  5684. */
  5685. element( indexNode ) {
  5686. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5687. }
  5688. /**
  5689. * Sets the node type which automatically defines the internal
  5690. * uniform type.
  5691. *
  5692. * @param {string} uniformType - The type to set.
  5693. */
  5694. setNodeType( uniformType ) {
  5695. const node = uniform( null, uniformType ).getSelf();
  5696. if ( this.group !== null ) {
  5697. node.setGroup( this.group );
  5698. }
  5699. this.node = node;
  5700. }
  5701. /**
  5702. * This method is overwritten since the node type is inferred from
  5703. * the type of the reference node.
  5704. *
  5705. * @param {NodeBuilder} builder - The current node builder.
  5706. * @return {string} The node type.
  5707. */
  5708. getNodeType( builder ) {
  5709. if ( this.node === null ) {
  5710. this.updateReference( builder );
  5711. this.updateValue();
  5712. }
  5713. return this.node.getNodeType( builder );
  5714. }
  5715. /**
  5716. * Returns the property value from the given referred object.
  5717. *
  5718. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5719. * @return {any} The value.
  5720. */
  5721. getValueFromReference( object = this.reference ) {
  5722. const { properties } = this;
  5723. let value = object[ properties[ 0 ] ];
  5724. for ( let i = 1; i < properties.length; i ++ ) {
  5725. value = value[ properties[ i ] ];
  5726. }
  5727. return value;
  5728. }
  5729. /**
  5730. * Allows to update the reference based on the given state. The state is only
  5731. * evaluated {@link ReferenceBaseNode#object} is not set.
  5732. *
  5733. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5734. * @return {Object} The updated reference.
  5735. */
  5736. updateReference( state ) {
  5737. this.reference = this.object !== null ? this.object : state.object;
  5738. return this.reference;
  5739. }
  5740. /**
  5741. * The output of the reference node is the internal uniform node.
  5742. *
  5743. * @return {UniformNode} The output node.
  5744. */
  5745. setup() {
  5746. this.updateValue();
  5747. return this.node;
  5748. }
  5749. /**
  5750. * Overwritten to update the internal uniform value.
  5751. *
  5752. * @param {NodeFrame} frame - A reference to the current node frame.
  5753. */
  5754. update( /*frame*/ ) {
  5755. this.updateValue();
  5756. }
  5757. /**
  5758. * Retrieves the value from the referred object property and uses it
  5759. * to updated the internal uniform.
  5760. */
  5761. updateValue() {
  5762. if ( this.node === null ) this.setNodeType( this.uniformType );
  5763. const value = this.getValueFromReference();
  5764. if ( Array.isArray( value ) ) {
  5765. this.node.array = value;
  5766. } else {
  5767. this.node.value = value;
  5768. }
  5769. }
  5770. }
  5771. /**
  5772. * TSL function for creating a reference base node.
  5773. *
  5774. * @tsl
  5775. * @function
  5776. * @param {string} name - The name of the property the node refers to.
  5777. * @param {string} type - The uniform type that should be used to represent the property value.
  5778. * @param {Object} object - The object the property belongs to.
  5779. * @returns {ReferenceBaseNode}
  5780. */
  5781. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5782. /**
  5783. * This node is a special type of reference node which is intended
  5784. * for linking renderer properties with node values.
  5785. * ```js
  5786. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5787. * ```
  5788. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5789. * automatically be updated.
  5790. *
  5791. * @augments ReferenceBaseNode
  5792. */
  5793. class RendererReferenceNode extends ReferenceBaseNode {
  5794. static get type() {
  5795. return 'RendererReferenceNode';
  5796. }
  5797. /**
  5798. * Constructs a new renderer reference node.
  5799. *
  5800. * @param {string} property - The name of the property the node refers to.
  5801. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5802. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5803. * the node refers to the renderer of the current state.
  5804. */
  5805. constructor( property, inputType, renderer = null ) {
  5806. super( property, inputType, renderer );
  5807. /**
  5808. * The renderer the property belongs to. When no renderer is set,
  5809. * the node refers to the renderer of the current state.
  5810. *
  5811. * @type {?Renderer}
  5812. * @default null
  5813. */
  5814. this.renderer = renderer;
  5815. this.setGroup( renderGroup );
  5816. }
  5817. /**
  5818. * Updates the reference based on the given state. The state is only evaluated
  5819. * {@link RendererReferenceNode#renderer} is not set.
  5820. *
  5821. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5822. * @return {Object} The updated reference.
  5823. */
  5824. updateReference( state ) {
  5825. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5826. return this.reference;
  5827. }
  5828. }
  5829. /**
  5830. * TSL function for creating a renderer reference node.
  5831. *
  5832. * @tsl
  5833. * @function
  5834. * @param {string} name - The name of the property the node refers to.
  5835. * @param {string} type - The uniform type that should be used to represent the property value.
  5836. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5837. * the node refers to the renderer of the current state.
  5838. * @returns {RendererReferenceNode}
  5839. */
  5840. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5841. /**
  5842. * This node represents a tone mapping operation.
  5843. *
  5844. * @augments TempNode
  5845. */
  5846. class ToneMappingNode extends TempNode {
  5847. static get type() {
  5848. return 'ToneMappingNode';
  5849. }
  5850. /**
  5851. * Constructs a new tone mapping node.
  5852. *
  5853. * @param {number} toneMapping - The tone mapping type.
  5854. * @param {Node} exposureNode - The tone mapping exposure.
  5855. * @param {Node} [colorNode=null] - The color node to process.
  5856. */
  5857. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5858. super( 'vec3' );
  5859. /**
  5860. * The tone mapping type.
  5861. *
  5862. * @type {number}
  5863. */
  5864. this.toneMapping = toneMapping;
  5865. /**
  5866. * The tone mapping exposure.
  5867. *
  5868. * @type {Node}
  5869. * @default null
  5870. */
  5871. this.exposureNode = exposureNode;
  5872. /**
  5873. * Represents the color to process.
  5874. *
  5875. * @type {?Node}
  5876. * @default null
  5877. */
  5878. this.colorNode = colorNode;
  5879. }
  5880. /**
  5881. * Overwrites the default `customCacheKey()` implementation by including the tone
  5882. * mapping type into the cache key.
  5883. *
  5884. * @return {number} The hash.
  5885. */
  5886. customCacheKey() {
  5887. return hash$1( this.toneMapping );
  5888. }
  5889. setup( builder ) {
  5890. const colorNode = this.colorNode || builder.context.color;
  5891. const toneMapping = this.toneMapping;
  5892. if ( toneMapping === NoToneMapping ) return colorNode;
  5893. let outputNode = null;
  5894. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5895. if ( toneMappingFn !== null ) {
  5896. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5897. } else {
  5898. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5899. outputNode = colorNode;
  5900. }
  5901. return outputNode;
  5902. }
  5903. }
  5904. /**
  5905. * TSL function for creating a tone mapping node.
  5906. *
  5907. * @tsl
  5908. * @function
  5909. * @param {number} mapping - The tone mapping type.
  5910. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5911. * @param {Node<vec3> | Color} color - The color node to process.
  5912. * @returns {ToneMappingNode<vec3>}
  5913. */
  5914. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5915. /**
  5916. * TSL object that represents the global tone mapping exposure of the renderer.
  5917. *
  5918. * @tsl
  5919. * @type {RendererReferenceNode<vec3>}
  5920. */
  5921. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5922. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5923. /**
  5924. * In earlier `three.js` versions it was only possible to define attribute data
  5925. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5926. * on the node level.
  5927. * ```js
  5928. * const geometry = new THREE.PlaneGeometry();
  5929. * const positionAttribute = geometry.getAttribute( 'position' );
  5930. *
  5931. * const colors = [];
  5932. * for ( let i = 0; i < position.count; i ++ ) {
  5933. * colors.push( 1, 0, 0 );
  5934. * }
  5935. *
  5936. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5937. * ```
  5938. * This new approach is especially interesting when geometry data are generated via
  5939. * compute shaders. The below line converts a storage buffer into an attribute node.
  5940. * ```js
  5941. * material.positionNode = positionBuffer.toAttribute();
  5942. * ```
  5943. * @augments InputNode
  5944. */
  5945. class BufferAttributeNode extends InputNode {
  5946. static get type() {
  5947. return 'BufferAttributeNode';
  5948. }
  5949. /**
  5950. * Constructs a new buffer attribute node.
  5951. *
  5952. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5953. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5954. * @param {number} [bufferStride=0] - The buffer stride.
  5955. * @param {number} [bufferOffset=0] - The buffer offset.
  5956. */
  5957. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5958. super( value, bufferType );
  5959. /**
  5960. * This flag can be used for type testing.
  5961. *
  5962. * @type {boolean}
  5963. * @readonly
  5964. * @default true
  5965. */
  5966. this.isBufferNode = true;
  5967. /**
  5968. * The buffer type (e.g. `'vec3'`).
  5969. *
  5970. * @type {?string}
  5971. * @default null
  5972. */
  5973. this.bufferType = bufferType;
  5974. /**
  5975. * The buffer stride.
  5976. *
  5977. * @type {number}
  5978. * @default 0
  5979. */
  5980. this.bufferStride = bufferStride;
  5981. /**
  5982. * The buffer offset.
  5983. *
  5984. * @type {number}
  5985. * @default 0
  5986. */
  5987. this.bufferOffset = bufferOffset;
  5988. /**
  5989. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5990. * if you are planning to update the attribute data per frame.
  5991. *
  5992. * @type {number}
  5993. * @default StaticDrawUsage
  5994. */
  5995. this.usage = StaticDrawUsage;
  5996. /**
  5997. * Whether the attribute is instanced or not.
  5998. *
  5999. * @type {boolean}
  6000. * @default false
  6001. */
  6002. this.instanced = false;
  6003. /**
  6004. * A reference to the buffer attribute.
  6005. *
  6006. * @type {?BufferAttribute}
  6007. * @default null
  6008. */
  6009. this.attribute = null;
  6010. /**
  6011. * `BufferAttributeNode` sets this property to `true` by default.
  6012. *
  6013. * @type {boolean}
  6014. * @default true
  6015. */
  6016. this.global = true;
  6017. if ( value && value.isBufferAttribute === true ) {
  6018. this.attribute = value;
  6019. this.usage = value.usage;
  6020. this.instanced = value.isInstancedBufferAttribute;
  6021. }
  6022. }
  6023. /**
  6024. * This method is overwritten since the attribute data might be shared
  6025. * and thus the hash should be shared as well.
  6026. *
  6027. * @param {NodeBuilder} builder - The current node builder.
  6028. * @return {string} The hash.
  6029. */
  6030. getHash( builder ) {
  6031. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6032. let bufferData = builder.globalCache.getData( this.value );
  6033. if ( bufferData === undefined ) {
  6034. bufferData = {
  6035. node: this
  6036. };
  6037. builder.globalCache.setData( this.value, bufferData );
  6038. }
  6039. return bufferData.node.uuid;
  6040. }
  6041. return this.uuid;
  6042. }
  6043. /**
  6044. * This method is overwritten since the node type is inferred from
  6045. * the buffer attribute.
  6046. *
  6047. * @param {NodeBuilder} builder - The current node builder.
  6048. * @return {string} The node type.
  6049. */
  6050. getNodeType( builder ) {
  6051. if ( this.bufferType === null ) {
  6052. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6053. }
  6054. return this.bufferType;
  6055. }
  6056. /**
  6057. * Depending on which value was passed to the node, `setup()` behaves
  6058. * differently. If no instance of `BufferAttribute` was passed, the method
  6059. * creates an internal attribute and configures it respectively.
  6060. *
  6061. * @param {NodeBuilder} builder - The current node builder.
  6062. */
  6063. setup( builder ) {
  6064. if ( this.attribute !== null ) return;
  6065. const type = this.getNodeType( builder );
  6066. const array = this.value;
  6067. const itemSize = builder.getTypeLength( type );
  6068. const stride = this.bufferStride || itemSize;
  6069. const offset = this.bufferOffset;
  6070. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6071. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6072. buffer.setUsage( this.usage );
  6073. this.attribute = bufferAttribute;
  6074. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6075. }
  6076. /**
  6077. * Generates the code snippet of the buffer attribute node.
  6078. *
  6079. * @param {NodeBuilder} builder - The current node builder.
  6080. * @return {string} The generated code snippet.
  6081. */
  6082. generate( builder ) {
  6083. const nodeType = this.getNodeType( builder );
  6084. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6085. const propertyName = builder.getPropertyName( nodeAttribute );
  6086. let output = null;
  6087. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6088. this.name = propertyName;
  6089. output = propertyName;
  6090. } else {
  6091. const nodeVarying = varying( this );
  6092. output = nodeVarying.build( builder, nodeType );
  6093. }
  6094. return output;
  6095. }
  6096. /**
  6097. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6098. *
  6099. * @param {NodeBuilder} builder - The current node builder.
  6100. * @return {string} The input type.
  6101. */
  6102. getInputType( /*builder*/ ) {
  6103. return 'bufferAttribute';
  6104. }
  6105. /**
  6106. * Sets the `usage` property to the given value.
  6107. *
  6108. * @param {number} value - The usage to set.
  6109. * @return {BufferAttributeNode} A reference to this node.
  6110. */
  6111. setUsage( value ) {
  6112. this.usage = value;
  6113. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6114. this.attribute.usage = value;
  6115. }
  6116. return this;
  6117. }
  6118. /**
  6119. * Sets the `instanced` property to the given value.
  6120. *
  6121. * @param {boolean} value - The value to set.
  6122. * @return {BufferAttributeNode} A reference to this node.
  6123. */
  6124. setInstanced( value ) {
  6125. this.instanced = value;
  6126. return this;
  6127. }
  6128. }
  6129. /**
  6130. * TSL function for creating a buffer attribute node.
  6131. *
  6132. * @tsl
  6133. * @function
  6134. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6135. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6136. * @param {number} [stride=0] - The buffer stride.
  6137. * @param {number} [offset=0] - The buffer offset.
  6138. * @returns {BufferAttributeNode}
  6139. */
  6140. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6141. /**
  6142. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6143. * Use this function if attribute data are updated per frame.
  6144. *
  6145. * @tsl
  6146. * @function
  6147. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6148. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6149. * @param {number} [stride=0] - The buffer stride.
  6150. * @param {number} [offset=0] - The buffer offset.
  6151. * @returns {BufferAttributeNode}
  6152. */
  6153. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6154. /**
  6155. * TSL function for creating a buffer attribute node but with enabled instancing
  6156. *
  6157. * @tsl
  6158. * @function
  6159. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6160. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6161. * @param {number} [stride=0] - The buffer stride.
  6162. * @param {number} [offset=0] - The buffer offset.
  6163. * @returns {BufferAttributeNode}
  6164. */
  6165. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6166. /**
  6167. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6168. *
  6169. * @tsl
  6170. * @function
  6171. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6172. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6173. * @param {number} [stride=0] - The buffer stride.
  6174. * @param {number} [offset=0] - The buffer offset.
  6175. * @returns {BufferAttributeNode}
  6176. */
  6177. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6178. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6179. /**
  6180. * TODO
  6181. *
  6182. * @augments Node
  6183. */
  6184. class ComputeNode extends Node {
  6185. static get type() {
  6186. return 'ComputeNode';
  6187. }
  6188. /**
  6189. * Constructs a new compute node.
  6190. *
  6191. * @param {Node} computeNode - TODO
  6192. * @param {number} count - TODO.
  6193. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6194. */
  6195. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  6196. super( 'void' );
  6197. /**
  6198. * This flag can be used for type testing.
  6199. *
  6200. * @type {boolean}
  6201. * @readonly
  6202. * @default true
  6203. */
  6204. this.isComputeNode = true;
  6205. /**
  6206. * TODO
  6207. *
  6208. * @type {Node}
  6209. */
  6210. this.computeNode = computeNode;
  6211. /**
  6212. * TODO
  6213. *
  6214. * @type {number}
  6215. */
  6216. this.count = count;
  6217. /**
  6218. * TODO
  6219. *
  6220. * @type {Array<number>}
  6221. * @default [64]
  6222. */
  6223. this.workgroupSize = workgroupSize;
  6224. /**
  6225. * TODO
  6226. *
  6227. * @type {number}
  6228. */
  6229. this.dispatchCount = 0;
  6230. /**
  6231. * TODO
  6232. *
  6233. * @type {number}
  6234. */
  6235. this.version = 1;
  6236. /**
  6237. * The name or label of the uniform.
  6238. *
  6239. * @type {string}
  6240. * @default ''
  6241. */
  6242. this.name = '';
  6243. /**
  6244. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6245. * is executed once per object by default.
  6246. *
  6247. * @type {string}
  6248. * @default 'object'
  6249. */
  6250. this.updateBeforeType = NodeUpdateType.OBJECT;
  6251. /**
  6252. * TODO
  6253. *
  6254. * @type {?Function}
  6255. */
  6256. this.onInitFunction = null;
  6257. this.updateDispatchCount();
  6258. }
  6259. /**
  6260. * Executes the `dispose` event for this node.
  6261. */
  6262. dispose() {
  6263. this.dispatchEvent( { type: 'dispose' } );
  6264. }
  6265. /**
  6266. * Sets the {@link ComputeNode#name} property.
  6267. *
  6268. * @param {string} name - The name of the uniform.
  6269. * @return {ComputeNode} A reference to this node.
  6270. */
  6271. label( name ) {
  6272. this.name = name;
  6273. return this;
  6274. }
  6275. /**
  6276. * TODO
  6277. */
  6278. updateDispatchCount() {
  6279. const { count, workgroupSize } = this;
  6280. let size = workgroupSize[ 0 ];
  6281. for ( let i = 1; i < workgroupSize.length; i ++ )
  6282. size *= workgroupSize[ i ];
  6283. this.dispatchCount = Math.ceil( count / size );
  6284. }
  6285. /**
  6286. * TODO
  6287. *
  6288. * @param {Function} callback - TODO.
  6289. * @return {ComputeNode} A reference to this node.
  6290. */
  6291. onInit( callback ) {
  6292. this.onInitFunction = callback;
  6293. return this;
  6294. }
  6295. /**
  6296. * The method execute the compute for this node.
  6297. *
  6298. * @param {NodeFrame} frame - A reference to the current node frame.
  6299. */
  6300. updateBefore( { renderer } ) {
  6301. renderer.compute( this );
  6302. }
  6303. setup( builder ) {
  6304. const result = this.computeNode.build( builder );
  6305. if ( result ) {
  6306. const properties = builder.getNodeProperties( this );
  6307. properties.outputComputeNode = result.outputNode;
  6308. result.outputNode = null;
  6309. }
  6310. return result;
  6311. }
  6312. generate( builder, output ) {
  6313. const { shaderStage } = builder;
  6314. if ( shaderStage === 'compute' ) {
  6315. const snippet = this.computeNode.build( builder, 'void' );
  6316. if ( snippet !== '' ) {
  6317. builder.addLineFlowCode( snippet, this );
  6318. }
  6319. } else {
  6320. const properties = builder.getNodeProperties( this );
  6321. const outputComputeNode = properties.outputComputeNode;
  6322. if ( outputComputeNode ) {
  6323. return outputComputeNode.build( builder, output );
  6324. }
  6325. }
  6326. }
  6327. }
  6328. /**
  6329. * TSL function for creating a compute node.
  6330. *
  6331. * @tsl
  6332. * @function
  6333. * @param {Node} node - TODO
  6334. * @param {number} count - TODO.
  6335. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6336. * @returns {AtomicFunctionNode}
  6337. */
  6338. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6339. addMethodChaining( 'compute', compute );
  6340. /**
  6341. * This node can be used as a cache management component for another node.
  6342. * Caching is in general used by default in {@link NodeBuilder} but this node
  6343. * allows the usage of a shared parent cache during the build process.
  6344. *
  6345. * @augments Node
  6346. */
  6347. class CacheNode extends Node {
  6348. static get type() {
  6349. return 'CacheNode';
  6350. }
  6351. /**
  6352. * Constructs a new cache node.
  6353. *
  6354. * @param {Node} node - The node that should be cached.
  6355. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6356. */
  6357. constructor( node, parent = true ) {
  6358. super();
  6359. /**
  6360. * The node that should be cached.
  6361. *
  6362. * @type {Node}
  6363. */
  6364. this.node = node;
  6365. /**
  6366. * Whether this node refers to a shared parent cache or not.
  6367. *
  6368. * @type {boolean}
  6369. * @default true
  6370. */
  6371. this.parent = parent;
  6372. /**
  6373. * This flag can be used for type testing.
  6374. *
  6375. * @type {boolean}
  6376. * @readonly
  6377. * @default true
  6378. */
  6379. this.isCacheNode = true;
  6380. }
  6381. getNodeType( builder ) {
  6382. const previousCache = builder.getCache();
  6383. const cache = builder.getCacheFromNode( this, this.parent );
  6384. builder.setCache( cache );
  6385. const nodeType = this.node.getNodeType( builder );
  6386. builder.setCache( previousCache );
  6387. return nodeType;
  6388. }
  6389. build( builder, ...params ) {
  6390. const previousCache = builder.getCache();
  6391. const cache = builder.getCacheFromNode( this, this.parent );
  6392. builder.setCache( cache );
  6393. const data = this.node.build( builder, ...params );
  6394. builder.setCache( previousCache );
  6395. return data;
  6396. }
  6397. }
  6398. /**
  6399. * TSL function for creating a cache node.
  6400. *
  6401. * @tsl
  6402. * @function
  6403. * @param {Node} node - The node that should be cached.
  6404. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6405. * @returns {CacheNode}
  6406. */
  6407. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6408. addMethodChaining( 'cache', cache );
  6409. /**
  6410. * The class generates the code of a given node but returns another node in the output.
  6411. * This can be used to call a method or node that does not return a value, i.e.
  6412. * type `void` on an input where returning a value is required. Example:
  6413. *
  6414. * ```js
  6415. * material.colorNode = myColor.bypass( runVoidFn() )
  6416. *```
  6417. *
  6418. * @augments Node
  6419. */
  6420. class BypassNode extends Node {
  6421. static get type() {
  6422. return 'BypassNode';
  6423. }
  6424. /**
  6425. * Constructs a new bypass node.
  6426. *
  6427. * @param {Node} outputNode - The output node.
  6428. * @param {Node} callNode - The call node.
  6429. */
  6430. constructor( outputNode, callNode ) {
  6431. super();
  6432. /**
  6433. * This flag can be used for type testing.
  6434. *
  6435. * @type {boolean}
  6436. * @readonly
  6437. * @default true
  6438. */
  6439. this.isBypassNode = true;
  6440. /**
  6441. * The output node.
  6442. *
  6443. * @type {Node}
  6444. */
  6445. this.outputNode = outputNode;
  6446. /**
  6447. * The call node.
  6448. *
  6449. * @type {Node}
  6450. */
  6451. this.callNode = callNode;
  6452. }
  6453. getNodeType( builder ) {
  6454. return this.outputNode.getNodeType( builder );
  6455. }
  6456. generate( builder ) {
  6457. const snippet = this.callNode.build( builder, 'void' );
  6458. if ( snippet !== '' ) {
  6459. builder.addLineFlowCode( snippet, this );
  6460. }
  6461. return this.outputNode.build( builder );
  6462. }
  6463. }
  6464. /**
  6465. * TSL function for creating a bypass node.
  6466. *
  6467. * @tsl
  6468. * @function
  6469. * @param {Node} outputNode - The output node.
  6470. * @param {Node} callNode - The call node.
  6471. * @returns {BypassNode}
  6472. */
  6473. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6474. addMethodChaining( 'bypass', bypass );
  6475. /**
  6476. * This node allows to remap a node value from one range into another. E.g a value of
  6477. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6478. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6479. *
  6480. * @augments Node
  6481. */
  6482. class RemapNode extends Node {
  6483. static get type() {
  6484. return 'RemapNode';
  6485. }
  6486. /**
  6487. * Constructs a new remap node.
  6488. *
  6489. * @param {Node} node - The node that should be remapped.
  6490. * @param {Node} inLowNode - The source or current lower bound of the range.
  6491. * @param {Node} inHighNode - The source or current upper bound of the range.
  6492. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6493. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6494. */
  6495. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6496. super();
  6497. /**
  6498. * The node that should be remapped.
  6499. *
  6500. * @type {Node}
  6501. */
  6502. this.node = node;
  6503. /**
  6504. * The source or current lower bound of the range.
  6505. *
  6506. * @type {Node}
  6507. */
  6508. this.inLowNode = inLowNode;
  6509. /**
  6510. * The source or current upper bound of the range.
  6511. *
  6512. * @type {Node}
  6513. */
  6514. this.inHighNode = inHighNode;
  6515. /**
  6516. * The target lower bound of the range.
  6517. *
  6518. * @type {Node}
  6519. * @default float(0)
  6520. */
  6521. this.outLowNode = outLowNode;
  6522. /**
  6523. * The target upper bound of the range.
  6524. *
  6525. * @type {Node}
  6526. * @default float(1)
  6527. */
  6528. this.outHighNode = outHighNode;
  6529. /**
  6530. * Whether the node value should be clamped before
  6531. * remapping it to the target range.
  6532. *
  6533. * @type {boolean}
  6534. * @default true
  6535. */
  6536. this.doClamp = true;
  6537. }
  6538. setup() {
  6539. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6540. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6541. if ( doClamp === true ) t = t.clamp();
  6542. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6543. }
  6544. }
  6545. /**
  6546. * TSL function for creating a remap node.
  6547. *
  6548. * @tsl
  6549. * @function
  6550. * @param {Node} node - The node that should be remapped.
  6551. * @param {Node} inLowNode - The source or current lower bound of the range.
  6552. * @param {Node} inHighNode - The source or current upper bound of the range.
  6553. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6554. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6555. * @returns {RemapNode}
  6556. */
  6557. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  6558. /**
  6559. * TSL function for creating a remap node, but with enabled clamping.
  6560. *
  6561. * @tsl
  6562. * @function
  6563. * @param {Node} node - The node that should be remapped.
  6564. * @param {Node} inLowNode - The source or current lower bound of the range.
  6565. * @param {Node} inHighNode - The source or current upper bound of the range.
  6566. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6567. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6568. * @returns {RemapNode}
  6569. */
  6570. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  6571. addMethodChaining( 'remap', remap );
  6572. addMethodChaining( 'remapClamp', remapClamp );
  6573. /**
  6574. * This class can be used to implement basic expressions in shader code.
  6575. * Basic examples for that are `return`, `continue` or `discard` statements.
  6576. *
  6577. * @augments Node
  6578. */
  6579. class ExpressionNode extends Node {
  6580. static get type() {
  6581. return 'ExpressionNode';
  6582. }
  6583. /**
  6584. * Constructs a new expression node.
  6585. *
  6586. * @param {string} [snippet=''] - The native code snippet.
  6587. * @param {string} [nodeType='void'] - The node type.
  6588. */
  6589. constructor( snippet = '', nodeType = 'void' ) {
  6590. super( nodeType );
  6591. /**
  6592. * The native code snippet.
  6593. *
  6594. * @type {string}
  6595. * @default ''
  6596. */
  6597. this.snippet = snippet;
  6598. }
  6599. generate( builder, output ) {
  6600. const type = this.getNodeType( builder );
  6601. const snippet = this.snippet;
  6602. if ( type === 'void' ) {
  6603. builder.addLineFlowCode( snippet, this );
  6604. } else {
  6605. return builder.format( snippet, type, output );
  6606. }
  6607. }
  6608. }
  6609. /**
  6610. * TSL function for creating an expression node.
  6611. *
  6612. * @tsl
  6613. * @function
  6614. * @param {string} [snippet] - The native code snippet.
  6615. * @param {?string} [nodeType='void'] - The node type.
  6616. * @returns {ExpressionNode}
  6617. */
  6618. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  6619. /**
  6620. * Represents a `discard` shader operation in TSL.
  6621. *
  6622. * @tsl
  6623. * @function
  6624. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6625. * @return {Node} The `discard` expression.
  6626. */
  6627. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  6628. /**
  6629. * Represents a `return` shader operation in TSL.
  6630. *
  6631. * @tsl
  6632. * @function
  6633. * @return {ExpressionNode} The `return` expression.
  6634. */
  6635. const Return = () => expression( 'return' ).toStack();
  6636. addMethodChaining( 'discard', Discard );
  6637. /**
  6638. * Normally, tone mapping and color conversion happens automatically
  6639. * before outputting pixel too the default (screen) framebuffer. In certain
  6640. * post processing setups this happens to late because certain effects
  6641. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6642. * to apply tone mapping and color space conversion at an arbitrary point
  6643. * in the effect chain.
  6644. *
  6645. * When applying tone mapping and color space conversion manually with this node,
  6646. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6647. *
  6648. * ```js
  6649. * const postProcessing = new PostProcessing( renderer );
  6650. * postProcessing.outputColorTransform = false;
  6651. *
  6652. * const scenePass = pass( scene, camera );
  6653. * const outputPass = renderOutput( scenePass );
  6654. *
  6655. * postProcessing.outputNode = outputPass;
  6656. * ```
  6657. *
  6658. * @augments TempNode
  6659. */
  6660. class RenderOutputNode extends TempNode {
  6661. static get type() {
  6662. return 'RenderOutputNode';
  6663. }
  6664. /**
  6665. * Constructs a new render output node.
  6666. *
  6667. * @param {Node} colorNode - The color node to process.
  6668. * @param {?number} toneMapping - The tone mapping type.
  6669. * @param {?string} outputColorSpace - The output color space.
  6670. */
  6671. constructor( colorNode, toneMapping, outputColorSpace ) {
  6672. super( 'vec4' );
  6673. /**
  6674. * The color node to process.
  6675. *
  6676. * @type {Node}
  6677. */
  6678. this.colorNode = colorNode;
  6679. /**
  6680. * The tone mapping type.
  6681. *
  6682. * @type {?number}
  6683. */
  6684. this.toneMapping = toneMapping;
  6685. /**
  6686. * The output color space.
  6687. *
  6688. * @type {?string}
  6689. */
  6690. this.outputColorSpace = outputColorSpace;
  6691. /**
  6692. * This flag can be used for type testing.
  6693. *
  6694. * @type {boolean}
  6695. * @readonly
  6696. * @default true
  6697. */
  6698. this.isRenderOutputNode = true;
  6699. }
  6700. setup( { context } ) {
  6701. let outputNode = this.colorNode || context.color;
  6702. // tone mapping
  6703. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6704. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6705. if ( toneMapping !== NoToneMapping ) {
  6706. outputNode = outputNode.toneMapping( toneMapping );
  6707. }
  6708. // working to output color space
  6709. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6710. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6711. }
  6712. return outputNode;
  6713. }
  6714. }
  6715. /**
  6716. * TSL function for creating a posterize node.
  6717. *
  6718. * @tsl
  6719. * @function
  6720. * @param {Node} color - The color node to process.
  6721. * @param {?number} [toneMapping=null] - The tone mapping type.
  6722. * @param {?string} [outputColorSpace=null] - The output color space.
  6723. * @returns {RenderOutputNode}
  6724. */
  6725. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6726. addMethodChaining( 'renderOutput', renderOutput );
  6727. class DebugNode extends TempNode {
  6728. static get type() {
  6729. return 'DebugNode';
  6730. }
  6731. constructor( node, callback = null ) {
  6732. super();
  6733. this.node = node;
  6734. this.callback = callback;
  6735. }
  6736. getNodeType( builder ) {
  6737. return this.node.getNodeType( builder );
  6738. }
  6739. setup( builder ) {
  6740. return this.node.build( builder );
  6741. }
  6742. analyze( builder ) {
  6743. return this.node.build( builder );
  6744. }
  6745. generate( builder ) {
  6746. const callback = this.callback;
  6747. const snippet = this.node.build( builder );
  6748. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  6749. const border = '-'.repeat( title.length );
  6750. let code = '';
  6751. code += '// #' + title + '#\n';
  6752. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  6753. code += '/* ... */ ' + snippet + ' /* ... */\n';
  6754. code += '// #' + border + '#\n';
  6755. if ( callback !== null ) {
  6756. callback( builder, code );
  6757. } else {
  6758. console.log( code );
  6759. }
  6760. return snippet;
  6761. }
  6762. }
  6763. /**
  6764. * TSL function for creating a debug node.
  6765. *
  6766. * @tsl
  6767. * @function
  6768. * @param {Node} node - The node to debug.
  6769. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  6770. * @returns {DebugNode}
  6771. */
  6772. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) );
  6773. addMethodChaining( 'debug', debug );
  6774. // Non-PURE exports list, side-effects are required here.
  6775. // TSL Base Syntax
  6776. function addNodeElement( name/*, nodeElement*/ ) {
  6777. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6778. }
  6779. /**
  6780. * Base class for representing shader attributes as nodes.
  6781. *
  6782. * @augments Node
  6783. */
  6784. class AttributeNode extends Node {
  6785. static get type() {
  6786. return 'AttributeNode';
  6787. }
  6788. /**
  6789. * Constructs a new attribute node.
  6790. *
  6791. * @param {string} attributeName - The name of the attribute.
  6792. * @param {?string} nodeType - The node type.
  6793. */
  6794. constructor( attributeName, nodeType = null ) {
  6795. super( nodeType );
  6796. /**
  6797. * `AttributeNode` sets this property to `true` by default.
  6798. *
  6799. * @type {boolean}
  6800. * @default true
  6801. */
  6802. this.global = true;
  6803. this._attributeName = attributeName;
  6804. }
  6805. getHash( builder ) {
  6806. return this.getAttributeName( builder );
  6807. }
  6808. getNodeType( builder ) {
  6809. let nodeType = this.nodeType;
  6810. if ( nodeType === null ) {
  6811. const attributeName = this.getAttributeName( builder );
  6812. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6813. const attribute = builder.geometry.getAttribute( attributeName );
  6814. nodeType = builder.getTypeFromAttribute( attribute );
  6815. } else {
  6816. nodeType = 'float';
  6817. }
  6818. }
  6819. return nodeType;
  6820. }
  6821. /**
  6822. * Sets the attribute name to the given value. The method can be
  6823. * overwritten in derived classes if the final name must be computed
  6824. * analytically.
  6825. *
  6826. * @param {string} attributeName - The name of the attribute.
  6827. * @return {AttributeNode} A reference to this node.
  6828. */
  6829. setAttributeName( attributeName ) {
  6830. this._attributeName = attributeName;
  6831. return this;
  6832. }
  6833. /**
  6834. * Returns the attribute name of this node. The method can be
  6835. * overwritten in derived classes if the final name must be computed
  6836. * analytically.
  6837. *
  6838. * @param {NodeBuilder} builder - The current node builder.
  6839. * @return {string} The attribute name.
  6840. */
  6841. getAttributeName( /*builder*/ ) {
  6842. return this._attributeName;
  6843. }
  6844. generate( builder ) {
  6845. const attributeName = this.getAttributeName( builder );
  6846. const nodeType = this.getNodeType( builder );
  6847. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6848. if ( geometryAttribute === true ) {
  6849. const attribute = builder.geometry.getAttribute( attributeName );
  6850. const attributeType = builder.getTypeFromAttribute( attribute );
  6851. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6852. if ( builder.shaderStage === 'vertex' ) {
  6853. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6854. } else {
  6855. const nodeVarying = varying( this );
  6856. return nodeVarying.build( builder, nodeType );
  6857. }
  6858. } else {
  6859. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6860. return builder.generateConst( nodeType );
  6861. }
  6862. }
  6863. serialize( data ) {
  6864. super.serialize( data );
  6865. data.global = this.global;
  6866. data._attributeName = this._attributeName;
  6867. }
  6868. deserialize( data ) {
  6869. super.deserialize( data );
  6870. this.global = data.global;
  6871. this._attributeName = data._attributeName;
  6872. }
  6873. }
  6874. /**
  6875. * TSL function for creating an attribute node.
  6876. *
  6877. * @tsl
  6878. * @function
  6879. * @param {string} name - The name of the attribute.
  6880. * @param {?string} [nodeType=null] - The node type.
  6881. * @returns {AttributeNode}
  6882. */
  6883. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  6884. /**
  6885. * TSL function for creating an uv attribute node with the given index.
  6886. *
  6887. * @tsl
  6888. * @function
  6889. * @param {number} [index=0] - The uv index.
  6890. * @return {AttributeNode<vec2>} The uv attribute node.
  6891. */
  6892. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6893. /**
  6894. * A node that represents the dimensions of a texture. The texture size is
  6895. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6896. * or `textureSize()`.
  6897. *
  6898. * @augments Node
  6899. */
  6900. class TextureSizeNode extends Node {
  6901. static get type() {
  6902. return 'TextureSizeNode';
  6903. }
  6904. /**
  6905. * Constructs a new texture size node.
  6906. *
  6907. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6908. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6909. */
  6910. constructor( textureNode, levelNode = null ) {
  6911. super( 'uvec2' );
  6912. /**
  6913. * This flag can be used for type testing.
  6914. *
  6915. * @type {boolean}
  6916. * @readonly
  6917. * @default true
  6918. */
  6919. this.isTextureSizeNode = true;
  6920. /**
  6921. * A texture node which size should be retrieved.
  6922. *
  6923. * @type {TextureNode}
  6924. */
  6925. this.textureNode = textureNode;
  6926. /**
  6927. * A level node which defines the requested mip.
  6928. *
  6929. * @type {Node<int>}
  6930. * @default null
  6931. */
  6932. this.levelNode = levelNode;
  6933. }
  6934. generate( builder, output ) {
  6935. const textureProperty = this.textureNode.build( builder, 'property' );
  6936. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6937. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6938. }
  6939. }
  6940. /**
  6941. * TSL function for creating a texture size node.
  6942. *
  6943. * @tsl
  6944. * @function
  6945. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6946. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  6947. * @returns {TextureSizeNode}
  6948. */
  6949. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  6950. /**
  6951. * A special type of uniform node that computes the
  6952. * maximum mipmap level for a given texture node.
  6953. *
  6954. * ```js
  6955. * const level = maxMipLevel( textureNode );
  6956. * ```
  6957. *
  6958. * @augments UniformNode
  6959. */
  6960. class MaxMipLevelNode extends UniformNode {
  6961. static get type() {
  6962. return 'MaxMipLevelNode';
  6963. }
  6964. /**
  6965. * Constructs a new max mip level node.
  6966. *
  6967. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6968. */
  6969. constructor( textureNode ) {
  6970. super( 0 );
  6971. /**
  6972. * The texture node to compute the max mip level for.
  6973. *
  6974. * @private
  6975. * @type {TextureNode}
  6976. */
  6977. this._textureNode = textureNode;
  6978. /**
  6979. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6980. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6981. *
  6982. * @type {string}
  6983. * @default 'frame'
  6984. */
  6985. this.updateType = NodeUpdateType.FRAME;
  6986. }
  6987. /**
  6988. * The texture node to compute the max mip level for.
  6989. *
  6990. * @readonly
  6991. * @type {TextureNode}
  6992. */
  6993. get textureNode() {
  6994. return this._textureNode;
  6995. }
  6996. /**
  6997. * The texture.
  6998. *
  6999. * @readonly
  7000. * @type {Texture}
  7001. */
  7002. get texture() {
  7003. return this._textureNode.value;
  7004. }
  7005. update() {
  7006. const texture = this.texture;
  7007. const images = texture.images;
  7008. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7009. if ( image && image.width !== undefined ) {
  7010. const { width, height } = image;
  7011. this.value = Math.log2( Math.max( width, height ) );
  7012. }
  7013. }
  7014. }
  7015. /**
  7016. * TSL function for creating a max mip level node.
  7017. *
  7018. * @tsl
  7019. * @function
  7020. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7021. * @returns {MaxMipLevelNode}
  7022. */
  7023. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7024. /**
  7025. * This type of uniform node represents a 2D texture.
  7026. *
  7027. * @augments UniformNode
  7028. */
  7029. class TextureNode extends UniformNode {
  7030. static get type() {
  7031. return 'TextureNode';
  7032. }
  7033. /**
  7034. * Constructs a new texture node.
  7035. *
  7036. * @param {Texture} value - The texture.
  7037. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7038. * @param {?Node<int>} [levelNode=null] - The level node.
  7039. * @param {?Node<float>} [biasNode=null] - The bias node.
  7040. */
  7041. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7042. super( value );
  7043. /**
  7044. * This flag can be used for type testing.
  7045. *
  7046. * @type {boolean}
  7047. * @readonly
  7048. * @default true
  7049. */
  7050. this.isTextureNode = true;
  7051. /**
  7052. * Represents the texture coordinates.
  7053. *
  7054. * @type {?Node<vec2|vec3>}
  7055. * @default null
  7056. */
  7057. this.uvNode = uvNode;
  7058. /**
  7059. * Represents the mip level that should be selected.
  7060. *
  7061. * @type {?Node<int>}
  7062. * @default null
  7063. */
  7064. this.levelNode = levelNode;
  7065. /**
  7066. * Represents the bias to be applied during level-of-detail computation.
  7067. *
  7068. * @type {?Node<float>}
  7069. * @default null
  7070. */
  7071. this.biasNode = biasNode;
  7072. /**
  7073. * Represents a reference value a texture sample is compared to.
  7074. *
  7075. * @type {?Node<float>}
  7076. * @default null
  7077. */
  7078. this.compareNode = null;
  7079. /**
  7080. * When using texture arrays, the depth node defines the layer to select.
  7081. *
  7082. * @type {?Node<int>}
  7083. * @default null
  7084. */
  7085. this.depthNode = null;
  7086. /**
  7087. * When defined, a texture is sampled using explicit gradients.
  7088. *
  7089. * @type {?Array<Node<vec2>>}
  7090. * @default null
  7091. */
  7092. this.gradNode = null;
  7093. /**
  7094. * Whether texture values should be sampled or fetched.
  7095. *
  7096. * @type {boolean}
  7097. * @default true
  7098. */
  7099. this.sampler = true;
  7100. /**
  7101. * Whether the uv transformation matrix should be
  7102. * automatically updated or not. Use `setUpdateMatrix()`
  7103. * if you want to change the value of the property.
  7104. *
  7105. * @type {boolean}
  7106. * @default false
  7107. */
  7108. this.updateMatrix = false;
  7109. /**
  7110. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7111. * sets the value to `frame` when the uv transformation matrix should
  7112. * automatically be updated.
  7113. *
  7114. * @type {string}
  7115. * @default 'none'
  7116. */
  7117. this.updateType = NodeUpdateType.NONE;
  7118. /**
  7119. * The reference node.
  7120. *
  7121. * @type {?Node}
  7122. * @default null
  7123. */
  7124. this.referenceNode = null;
  7125. /**
  7126. * The texture value is stored in a private property.
  7127. *
  7128. * @private
  7129. * @type {Texture}
  7130. */
  7131. this._value = value;
  7132. /**
  7133. * The uniform node that represents the uv transformation matrix.
  7134. *
  7135. * @private
  7136. * @type {?UniformNode<mat3>}
  7137. */
  7138. this._matrixUniform = null;
  7139. this.setUpdateMatrix( uvNode === null );
  7140. }
  7141. set value( value ) {
  7142. if ( this.referenceNode ) {
  7143. this.referenceNode.value = value;
  7144. } else {
  7145. this._value = value;
  7146. }
  7147. }
  7148. /**
  7149. * The texture value.
  7150. *
  7151. * @type {Texture}
  7152. */
  7153. get value() {
  7154. return this.referenceNode ? this.referenceNode.value : this._value;
  7155. }
  7156. /**
  7157. * Overwritten since the uniform hash is defined by the texture's UUID.
  7158. *
  7159. * @param {NodeBuilder} builder - The current node builder.
  7160. * @return {string} The uniform hash.
  7161. */
  7162. getUniformHash( /*builder*/ ) {
  7163. return this.value.uuid;
  7164. }
  7165. /**
  7166. * Overwritten since the node type is inferred from the texture type.
  7167. *
  7168. * @param {NodeBuilder} builder - The current node builder.
  7169. * @return {string} The node type.
  7170. */
  7171. getNodeType( /*builder*/ ) {
  7172. if ( this.value.isDepthTexture === true ) return 'float';
  7173. if ( this.value.type === UnsignedIntType ) {
  7174. return 'uvec4';
  7175. } else if ( this.value.type === IntType ) {
  7176. return 'ivec4';
  7177. }
  7178. return 'vec4';
  7179. }
  7180. /**
  7181. * Overwrites the default implementation to return a fixed value `'texture'`.
  7182. *
  7183. * @param {NodeBuilder} builder - The current node builder.
  7184. * @return {string} The input type.
  7185. */
  7186. getInputType( /*builder*/ ) {
  7187. return 'texture';
  7188. }
  7189. /**
  7190. * Returns a default uvs based on the current texture's channel.
  7191. *
  7192. * @return {AttributeNode<vec2>} The default uvs.
  7193. */
  7194. getDefaultUV() {
  7195. return uv( this.value.channel );
  7196. }
  7197. /**
  7198. * Overwritten to always return the texture reference of the node.
  7199. *
  7200. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7201. * @return {Texture} The texture reference.
  7202. */
  7203. updateReference( /*state*/ ) {
  7204. return this.value;
  7205. }
  7206. /**
  7207. * Transforms the given uv node with the texture transformation matrix.
  7208. *
  7209. * @param {Node} uvNode - The uv node to transform.
  7210. * @return {Node} The transformed uv node.
  7211. */
  7212. getTransformedUV( uvNode ) {
  7213. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7214. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7215. }
  7216. /**
  7217. * Defines whether the uv transformation matrix should automatically be updated or not.
  7218. *
  7219. * @param {boolean} value - The update toggle.
  7220. * @return {TextureNode} A reference to this node.
  7221. */
  7222. setUpdateMatrix( value ) {
  7223. this.updateMatrix = value;
  7224. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7225. return this;
  7226. }
  7227. /**
  7228. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7229. * to modify the uv node for correct sampling.
  7230. *
  7231. * @param {NodeBuilder} builder - The current node builder.
  7232. * @param {Node} uvNode - The uv node to setup.
  7233. * @return {Node} The updated uv node.
  7234. */
  7235. setupUV( builder, uvNode ) {
  7236. const texture = this.value;
  7237. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7238. if ( this.sampler ) {
  7239. uvNode = uvNode.flipY();
  7240. } else {
  7241. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7242. }
  7243. }
  7244. return uvNode;
  7245. }
  7246. /**
  7247. * Setups texture node by preparing the internal nodes for code generation.
  7248. *
  7249. * @param {NodeBuilder} builder - The current node builder.
  7250. */
  7251. setup( builder ) {
  7252. const properties = builder.getNodeProperties( this );
  7253. properties.referenceNode = this.referenceNode;
  7254. //
  7255. const texture = this.value;
  7256. if ( ! texture || texture.isTexture !== true ) {
  7257. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7258. }
  7259. //
  7260. let uvNode = this.uvNode;
  7261. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7262. uvNode = builder.context.getUV( this, builder );
  7263. }
  7264. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7265. if ( this.updateMatrix === true ) {
  7266. uvNode = this.getTransformedUV( uvNode );
  7267. }
  7268. uvNode = this.setupUV( builder, uvNode );
  7269. //
  7270. let levelNode = this.levelNode;
  7271. if ( levelNode === null && builder.context.getTextureLevel ) {
  7272. levelNode = builder.context.getTextureLevel( this );
  7273. }
  7274. //
  7275. properties.uvNode = uvNode;
  7276. properties.levelNode = levelNode;
  7277. properties.biasNode = this.biasNode;
  7278. properties.compareNode = this.compareNode;
  7279. properties.gradNode = this.gradNode;
  7280. properties.depthNode = this.depthNode;
  7281. }
  7282. /**
  7283. * Generates the uv code snippet.
  7284. *
  7285. * @param {NodeBuilder} builder - The current node builder.
  7286. * @param {Node} uvNode - The uv node to generate code for.
  7287. * @return {string} The generated code snippet.
  7288. */
  7289. generateUV( builder, uvNode ) {
  7290. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7291. }
  7292. /**
  7293. * Generates the snippet for the texture sampling.
  7294. *
  7295. * @param {NodeBuilder} builder - The current node builder.
  7296. * @param {string} textureProperty - The texture property.
  7297. * @param {string} uvSnippet - The uv snippet.
  7298. * @param {?string} levelSnippet - The level snippet.
  7299. * @param {?string} biasSnippet - The bias snippet.
  7300. * @param {?string} depthSnippet - The depth snippet.
  7301. * @param {?string} compareSnippet - The compare snippet.
  7302. * @param {?Array<string>} gradSnippet - The grad snippet.
  7303. * @return {string} The generated code snippet.
  7304. */
  7305. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7306. const texture = this.value;
  7307. let snippet;
  7308. if ( levelSnippet ) {
  7309. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7310. } else if ( biasSnippet ) {
  7311. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7312. } else if ( gradSnippet ) {
  7313. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7314. } else if ( compareSnippet ) {
  7315. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7316. } else if ( this.sampler === false ) {
  7317. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7318. } else {
  7319. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7320. }
  7321. return snippet;
  7322. }
  7323. /**
  7324. * Generates the code snippet of the texture node.
  7325. *
  7326. * @param {NodeBuilder} builder - The current node builder.
  7327. * @param {string} output - The current output.
  7328. * @return {string} The generated code snippet.
  7329. */
  7330. generate( builder, output ) {
  7331. const texture = this.value;
  7332. const properties = builder.getNodeProperties( this );
  7333. const textureProperty = super.generate( builder, 'property' );
  7334. if ( /^sampler/.test( output ) ) {
  7335. return textureProperty + '_sampler';
  7336. } else if ( builder.isReference( output ) ) {
  7337. return textureProperty;
  7338. } else {
  7339. const nodeData = builder.getDataFromNode( this );
  7340. let propertyName = nodeData.propertyName;
  7341. if ( propertyName === undefined ) {
  7342. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7343. const uvSnippet = this.generateUV( builder, uvNode );
  7344. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7345. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7346. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7347. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7348. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7349. const nodeVar = builder.getVarFromNode( this );
  7350. propertyName = builder.getPropertyName( nodeVar );
  7351. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7352. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7353. nodeData.snippet = snippet;
  7354. nodeData.propertyName = propertyName;
  7355. }
  7356. let snippet = propertyName;
  7357. const nodeType = this.getNodeType( builder );
  7358. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7359. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7360. }
  7361. return builder.format( snippet, nodeType, output );
  7362. }
  7363. }
  7364. /**
  7365. * Sets the sampler value.
  7366. *
  7367. * @param {boolean} value - The sampler value to set.
  7368. * @return {TextureNode} A reference to this texture node.
  7369. */
  7370. setSampler( value ) {
  7371. this.sampler = value;
  7372. return this;
  7373. }
  7374. /**
  7375. * Returns the sampler value.
  7376. *
  7377. * @return {boolean} The sampler value.
  7378. */
  7379. getSampler() {
  7380. return this.sampler;
  7381. }
  7382. // @TODO: Move to TSL
  7383. /**
  7384. * @function
  7385. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7386. *
  7387. * @param {Node} uvNode - The uv node.
  7388. * @return {TextureNode} A texture node representing the texture sample.
  7389. */
  7390. uv( uvNode ) { // @deprecated, r172
  7391. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7392. return this.sample( uvNode );
  7393. }
  7394. /**
  7395. * Samples the texture with the given uv node.
  7396. *
  7397. * @param {Node} uvNode - The uv node.
  7398. * @return {TextureNode} A texture node representing the texture sample.
  7399. */
  7400. sample( uvNode ) {
  7401. const textureNode = this.clone();
  7402. textureNode.uvNode = nodeObject( uvNode );
  7403. textureNode.referenceNode = this.getSelf();
  7404. return nodeObject( textureNode );
  7405. }
  7406. /**
  7407. * Samples a blurred version of the texture by defining an internal bias.
  7408. *
  7409. * @param {Node<float>} amountNode - How blurred the texture should be.
  7410. * @return {TextureNode} A texture node representing the texture sample.
  7411. */
  7412. blur( amountNode ) {
  7413. const textureNode = this.clone();
  7414. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7415. textureNode.referenceNode = this.getSelf();
  7416. const map = textureNode.value;
  7417. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7418. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7419. textureNode.biasNode = null;
  7420. }
  7421. return nodeObject( textureNode );
  7422. }
  7423. /**
  7424. * Samples a specific mip of the texture.
  7425. *
  7426. * @param {Node<int>} levelNode - The mip level to sample.
  7427. * @return {TextureNode} A texture node representing the texture sample.
  7428. */
  7429. level( levelNode ) {
  7430. const textureNode = this.clone();
  7431. textureNode.levelNode = nodeObject( levelNode );
  7432. textureNode.referenceNode = this.getSelf();
  7433. return nodeObject( textureNode );
  7434. }
  7435. /**
  7436. * Returns the texture size of the requested level.
  7437. *
  7438. * @param {Node<int>} levelNode - The level to compute the size for.
  7439. * @return {TextureSizeNode} The texture size.
  7440. */
  7441. size( levelNode ) {
  7442. return textureSize( this, levelNode );
  7443. }
  7444. /**
  7445. * Samples the texture with the given bias.
  7446. *
  7447. * @param {Node<float>} biasNode - The bias node.
  7448. * @return {TextureNode} A texture node representing the texture sample.
  7449. */
  7450. bias( biasNode ) {
  7451. const textureNode = this.clone();
  7452. textureNode.biasNode = nodeObject( biasNode );
  7453. textureNode.referenceNode = this.getSelf();
  7454. return nodeObject( textureNode );
  7455. }
  7456. /**
  7457. * Samples the texture by executing a compare operation.
  7458. *
  7459. * @param {Node<float>} compareNode - The node that defines the compare value.
  7460. * @return {TextureNode} A texture node representing the texture sample.
  7461. */
  7462. compare( compareNode ) {
  7463. const textureNode = this.clone();
  7464. textureNode.compareNode = nodeObject( compareNode );
  7465. textureNode.referenceNode = this.getSelf();
  7466. return nodeObject( textureNode );
  7467. }
  7468. /**
  7469. * Samples the texture using an explicit gradient.
  7470. *
  7471. * @param {Node<vec2>} gradNodeX - The gradX node.
  7472. * @param {Node<vec2>} gradNodeY - The gradY node.
  7473. * @return {TextureNode} A texture node representing the texture sample.
  7474. */
  7475. grad( gradNodeX, gradNodeY ) {
  7476. const textureNode = this.clone();
  7477. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7478. textureNode.referenceNode = this.getSelf();
  7479. return nodeObject( textureNode );
  7480. }
  7481. /**
  7482. * Samples the texture by defining a depth node.
  7483. *
  7484. * @param {Node<int>} depthNode - The depth node.
  7485. * @return {TextureNode} A texture node representing the texture sample.
  7486. */
  7487. depth( depthNode ) {
  7488. const textureNode = this.clone();
  7489. textureNode.depthNode = nodeObject( depthNode );
  7490. textureNode.referenceNode = this.getSelf();
  7491. return nodeObject( textureNode );
  7492. }
  7493. // --
  7494. serialize( data ) {
  7495. super.serialize( data );
  7496. data.value = this.value.toJSON( data.meta ).uuid;
  7497. data.sampler = this.sampler;
  7498. data.updateMatrix = this.updateMatrix;
  7499. data.updateType = this.updateType;
  7500. }
  7501. deserialize( data ) {
  7502. super.deserialize( data );
  7503. this.value = data.meta.textures[ data.value ];
  7504. this.sampler = data.sampler;
  7505. this.updateMatrix = data.updateMatrix;
  7506. this.updateType = data.updateType;
  7507. }
  7508. /**
  7509. * The update is used to implement the update of the uv transformation matrix.
  7510. */
  7511. update() {
  7512. const texture = this.value;
  7513. const matrixUniform = this._matrixUniform;
  7514. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7515. if ( texture.matrixAutoUpdate === true ) {
  7516. texture.updateMatrix();
  7517. }
  7518. }
  7519. /**
  7520. * Clones the texture node.
  7521. *
  7522. * @return {TextureNode} The cloned texture node.
  7523. */
  7524. clone() {
  7525. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7526. newNode.sampler = this.sampler;
  7527. newNode.depthNode = this.depthNode;
  7528. newNode.compareNode = this.compareNode;
  7529. newNode.gradNode = this.gradNode;
  7530. return newNode;
  7531. }
  7532. }
  7533. /**
  7534. * TSL function for creating a texture node.
  7535. *
  7536. * @tsl
  7537. * @function
  7538. * @param {Texture} value - The texture.
  7539. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7540. * @param {?Node<int>} [levelNode=null] - The level node.
  7541. * @param {?Node<float>} [biasNode=null] - The bias node.
  7542. * @returns {TextureNode}
  7543. */
  7544. const texture = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 );
  7545. /**
  7546. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7547. *
  7548. * @tsl
  7549. * @function
  7550. * @param {Texture} value - The texture.
  7551. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7552. * @param {?Node<int>} [levelNode=null] - The level node.
  7553. * @param {?Node<float>} [biasNode=null] - The bias node.
  7554. * @returns {TextureNode}
  7555. */
  7556. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7557. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7558. /**
  7559. * Converts a texture or texture node to a sampler.
  7560. *
  7561. * @tsl
  7562. * @function
  7563. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7564. * @returns {Node}
  7565. */
  7566. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7567. /**
  7568. * Converts a texture or texture node to a sampler comparison.
  7569. *
  7570. * @tsl
  7571. * @function
  7572. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7573. * @returns {Node}
  7574. */
  7575. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7576. /**
  7577. * A special type of uniform node which represents array-like data
  7578. * as uniform buffers. The access usually happens via `element()`
  7579. * which returns an instance of {@link ArrayElementNode}. For example:
  7580. *
  7581. * ```js
  7582. * const bufferNode = buffer( array, 'mat4', count );
  7583. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7584. * ```
  7585. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7586. * since it handles more input types and automatically cares about buffer paddings.
  7587. *
  7588. * @augments UniformNode
  7589. */
  7590. class BufferNode extends UniformNode {
  7591. static get type() {
  7592. return 'BufferNode';
  7593. }
  7594. /**
  7595. * Constructs a new buffer node.
  7596. *
  7597. * @param {Array<number>} value - Array-like buffer data.
  7598. * @param {string} bufferType - The data type of the buffer.
  7599. * @param {number} [bufferCount=0] - The count of buffer elements.
  7600. */
  7601. constructor( value, bufferType, bufferCount = 0 ) {
  7602. super( value, bufferType );
  7603. /**
  7604. * This flag can be used for type testing.
  7605. *
  7606. * @type {boolean}
  7607. * @readonly
  7608. * @default true
  7609. */
  7610. this.isBufferNode = true;
  7611. /**
  7612. * The data type of the buffer.
  7613. *
  7614. * @type {string}
  7615. */
  7616. this.bufferType = bufferType;
  7617. /**
  7618. * The uniform node that holds the value of the reference node.
  7619. *
  7620. * @type {number}
  7621. * @default 0
  7622. */
  7623. this.bufferCount = bufferCount;
  7624. }
  7625. /**
  7626. * The data type of the buffer elements.
  7627. *
  7628. * @param {NodeBuilder} builder - The current node builder.
  7629. * @return {string} The element type.
  7630. */
  7631. getElementType( builder ) {
  7632. return this.getNodeType( builder );
  7633. }
  7634. /**
  7635. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7636. *
  7637. * @param {NodeBuilder} builder - The current node builder.
  7638. * @return {string} The input type.
  7639. */
  7640. getInputType( /*builder*/ ) {
  7641. return 'buffer';
  7642. }
  7643. }
  7644. /**
  7645. * TSL function for creating a buffer node.
  7646. *
  7647. * @tsl
  7648. * @function
  7649. * @param {Array} value - Array-like buffer data.
  7650. * @param {string} type - The data type of a buffer element.
  7651. * @param {number} count - The count of buffer elements.
  7652. * @returns {BufferNode}
  7653. */
  7654. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7655. /**
  7656. * Represents the element access on uniform array nodes.
  7657. *
  7658. * @augments ArrayElementNode
  7659. */
  7660. class UniformArrayElementNode extends ArrayElementNode {
  7661. static get type() {
  7662. return 'UniformArrayElementNode';
  7663. }
  7664. /**
  7665. * Constructs a new buffer node.
  7666. *
  7667. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7668. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7669. */
  7670. constructor( uniformArrayNode, indexNode ) {
  7671. super( uniformArrayNode, indexNode );
  7672. /**
  7673. * This flag can be used for type testing.
  7674. *
  7675. * @type {boolean}
  7676. * @readonly
  7677. * @default true
  7678. */
  7679. this.isArrayBufferElementNode = true;
  7680. }
  7681. generate( builder ) {
  7682. const snippet = super.generate( builder );
  7683. const type = this.getNodeType();
  7684. const paddedType = this.node.getPaddedType();
  7685. return builder.format( snippet, paddedType, type );
  7686. }
  7687. }
  7688. /**
  7689. * Similar to {@link BufferNode} this module represents array-like data as
  7690. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7691. * data types in the array (e.g `three.js` primitives) and automatically
  7692. * manage buffer padding. It should be the first choice when working with
  7693. * uniforms buffers.
  7694. * ```js
  7695. * const tintColors = uniformArray( [
  7696. * new Color( 1, 0, 0 ),
  7697. * new Color( 0, 1, 0 ),
  7698. * new Color( 0, 0, 1 )
  7699. * ], 'color' );
  7700. *
  7701. * const redColor = tintColors.element( 0 );
  7702. *
  7703. * @augments BufferNode
  7704. */
  7705. class UniformArrayNode extends BufferNode {
  7706. static get type() {
  7707. return 'UniformArrayNode';
  7708. }
  7709. /**
  7710. * Constructs a new uniform array node.
  7711. *
  7712. * @param {Array<any>} value - Array holding the buffer data.
  7713. * @param {?string} [elementType=null] - The data type of a buffer element.
  7714. */
  7715. constructor( value, elementType = null ) {
  7716. super( null );
  7717. /**
  7718. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7719. * hold number primitives as well as three.js objects like vectors, matrices
  7720. * or colors.
  7721. *
  7722. * @type {Array<any>}
  7723. */
  7724. this.array = value;
  7725. /**
  7726. * The data type of an array element.
  7727. *
  7728. * @type {string}
  7729. */
  7730. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7731. /**
  7732. * The padded type. Uniform buffers must conform to a certain buffer layout
  7733. * so a separate type is computed to ensure correct buffer size.
  7734. *
  7735. * @type {string}
  7736. */
  7737. this.paddedType = this.getPaddedType();
  7738. /**
  7739. * Overwritten since uniform array nodes are updated per render.
  7740. *
  7741. * @type {string}
  7742. * @default 'render'
  7743. */
  7744. this.updateType = NodeUpdateType.RENDER;
  7745. /**
  7746. * This flag can be used for type testing.
  7747. *
  7748. * @type {boolean}
  7749. * @readonly
  7750. * @default true
  7751. */
  7752. this.isArrayBufferNode = true;
  7753. }
  7754. /**
  7755. * This method is overwritten since the node type is inferred from the
  7756. * {@link UniformArrayNode#paddedType}.
  7757. *
  7758. * @param {NodeBuilder} builder - The current node builder.
  7759. * @return {string} The node type.
  7760. */
  7761. getNodeType( /*builder*/ ) {
  7762. return this.paddedType;
  7763. }
  7764. /**
  7765. * The data type of the array elements.
  7766. *
  7767. * @param {NodeBuilder} builder - The current node builder.
  7768. * @return {string} The element type.
  7769. */
  7770. getElementType() {
  7771. return this.elementType;
  7772. }
  7773. /**
  7774. * Returns the padded type based on the element type.
  7775. *
  7776. * @return {string} The padded type.
  7777. */
  7778. getPaddedType() {
  7779. const elementType = this.elementType;
  7780. let paddedType = 'vec4';
  7781. if ( elementType === 'mat2' ) {
  7782. paddedType = 'mat2';
  7783. } else if ( /mat/.test( elementType ) === true ) {
  7784. paddedType = 'mat4';
  7785. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7786. paddedType = 'ivec4';
  7787. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7788. paddedType = 'uvec4';
  7789. }
  7790. return paddedType;
  7791. }
  7792. /**
  7793. * The update makes sure to correctly transfer the data from the (complex) objects
  7794. * in the array to the internal, correctly padded value buffer.
  7795. *
  7796. * @param {NodeFrame} frame - A reference to the current node frame.
  7797. */
  7798. update( /*frame*/ ) {
  7799. const { array, value } = this;
  7800. const elementType = this.elementType;
  7801. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7802. for ( let i = 0; i < array.length; i ++ ) {
  7803. const index = i * 4;
  7804. value[ index ] = array[ i ];
  7805. }
  7806. } else if ( elementType === 'color' ) {
  7807. for ( let i = 0; i < array.length; i ++ ) {
  7808. const index = i * 4;
  7809. const vector = array[ i ];
  7810. value[ index ] = vector.r;
  7811. value[ index + 1 ] = vector.g;
  7812. value[ index + 2 ] = vector.b || 0;
  7813. //value[ index + 3 ] = vector.a || 0;
  7814. }
  7815. } else if ( elementType === 'mat2' ) {
  7816. for ( let i = 0; i < array.length; i ++ ) {
  7817. const index = i * 4;
  7818. const matrix = array[ i ];
  7819. value[ index ] = matrix.elements[ 0 ];
  7820. value[ index + 1 ] = matrix.elements[ 1 ];
  7821. value[ index + 2 ] = matrix.elements[ 2 ];
  7822. value[ index + 3 ] = matrix.elements[ 3 ];
  7823. }
  7824. } else if ( elementType === 'mat3' ) {
  7825. for ( let i = 0; i < array.length; i ++ ) {
  7826. const index = i * 16;
  7827. const matrix = array[ i ];
  7828. value[ index ] = matrix.elements[ 0 ];
  7829. value[ index + 1 ] = matrix.elements[ 1 ];
  7830. value[ index + 2 ] = matrix.elements[ 2 ];
  7831. value[ index + 4 ] = matrix.elements[ 3 ];
  7832. value[ index + 5 ] = matrix.elements[ 4 ];
  7833. value[ index + 6 ] = matrix.elements[ 5 ];
  7834. value[ index + 8 ] = matrix.elements[ 6 ];
  7835. value[ index + 9 ] = matrix.elements[ 7 ];
  7836. value[ index + 10 ] = matrix.elements[ 8 ];
  7837. value[ index + 15 ] = 1;
  7838. }
  7839. } else if ( elementType === 'mat4' ) {
  7840. for ( let i = 0; i < array.length; i ++ ) {
  7841. const index = i * 16;
  7842. const matrix = array[ i ];
  7843. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7844. value[ index + i ] = matrix.elements[ i ];
  7845. }
  7846. }
  7847. } else {
  7848. for ( let i = 0; i < array.length; i ++ ) {
  7849. const index = i * 4;
  7850. const vector = array[ i ];
  7851. value[ index ] = vector.x;
  7852. value[ index + 1 ] = vector.y;
  7853. value[ index + 2 ] = vector.z || 0;
  7854. value[ index + 3 ] = vector.w || 0;
  7855. }
  7856. }
  7857. }
  7858. /**
  7859. * Implement the value buffer creation based on the array data.
  7860. *
  7861. * @param {NodeBuilder} builder - A reference to the current node builder.
  7862. * @return {null}
  7863. */
  7864. setup( builder ) {
  7865. const length = this.array.length;
  7866. const elementType = this.elementType;
  7867. let arrayType = Float32Array;
  7868. const paddedType = this.paddedType;
  7869. const paddedElementLength = builder.getTypeLength( paddedType );
  7870. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7871. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7872. this.value = new arrayType( length * paddedElementLength );
  7873. this.bufferCount = length;
  7874. this.bufferType = paddedType;
  7875. return super.setup( builder );
  7876. }
  7877. /**
  7878. * Overwrites the default `element()` method to provide element access
  7879. * based on {@link UniformArrayNode}.
  7880. *
  7881. * @param {IndexNode} indexNode - The index node.
  7882. * @return {UniformArrayElementNode}
  7883. */
  7884. element( indexNode ) {
  7885. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7886. }
  7887. }
  7888. /**
  7889. * TSL function for creating an uniform array node.
  7890. *
  7891. * @tsl
  7892. * @function
  7893. * @param {Array<any>} values - Array-like data.
  7894. * @param {?string} [nodeType] - The data type of the array elements.
  7895. * @returns {UniformArrayNode}
  7896. */
  7897. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7898. /**
  7899. * @tsl
  7900. * @function
  7901. * @deprecated since r168. Use {@link uniformArray} instead.
  7902. *
  7903. * @param {Array<any>} values - Array-like data.
  7904. * @param {string} nodeType - The data type of the array elements.
  7905. * @returns {UniformArrayNode}
  7906. */
  7907. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7908. console.warn( 'THREE.TSL: uniforms() has been renamed to uniformArray().' );
  7909. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7910. };
  7911. /**
  7912. * The node allows to set values for built-in shader variables. That is
  7913. * required for features like hardware-accelerated vertex clipping.
  7914. *
  7915. * @augments Node
  7916. */
  7917. class BuiltinNode extends Node {
  7918. /**
  7919. * Constructs a new builtin node.
  7920. *
  7921. * @param {string} name - The name of the built-in shader variable.
  7922. */
  7923. constructor( name ) {
  7924. super( 'float' );
  7925. /**
  7926. * The name of the built-in shader variable.
  7927. *
  7928. * @type {string}
  7929. */
  7930. this.name = name;
  7931. /**
  7932. * This flag can be used for type testing.
  7933. *
  7934. * @type {boolean}
  7935. * @readonly
  7936. * @default true
  7937. */
  7938. this.isBuiltinNode = true;
  7939. }
  7940. /**
  7941. * Generates the code snippet of the builtin node.
  7942. *
  7943. * @param {NodeBuilder} builder - The current node builder.
  7944. * @return {string} The generated code snippet.
  7945. */
  7946. generate( /* builder */ ) {
  7947. return this.name;
  7948. }
  7949. }
  7950. /**
  7951. * TSL function for creating a builtin node.
  7952. *
  7953. * @tsl
  7954. * @function
  7955. * @param {string} name - The name of the built-in shader variable.
  7956. * @returns {BuiltinNode}
  7957. */
  7958. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  7959. /**
  7960. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7961. *
  7962. * @tsl
  7963. * @type {UniformNode<uint>}
  7964. */
  7965. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).label( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  7966. /**
  7967. * TSL object that represents the `near` value of the camera used for the current render.
  7968. *
  7969. * @tsl
  7970. * @type {UniformNode<float>}
  7971. */
  7972. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7973. /**
  7974. * TSL object that represents the `far` value of the camera used for the current render.
  7975. *
  7976. * @tsl
  7977. * @type {UniformNode<float>}
  7978. */
  7979. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7980. /**
  7981. * TSL object that represents the projection matrix of the camera used for the current render.
  7982. *
  7983. * @tsl
  7984. * @type {UniformNode<mat4>}
  7985. */
  7986. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7987. let cameraProjectionMatrix;
  7988. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  7989. const matrices = [];
  7990. for ( const subCamera of camera.cameras ) {
  7991. matrices.push( subCamera.projectionMatrix );
  7992. }
  7993. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7994. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7995. } else {
  7996. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7997. }
  7998. return cameraProjectionMatrix;
  7999. } ).once() )();
  8000. /**
  8001. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8002. *
  8003. * @tsl
  8004. * @type {UniformNode<mat4>}
  8005. */
  8006. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8007. let cameraProjectionMatrixInverse;
  8008. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8009. const matrices = [];
  8010. for ( const subCamera of camera.cameras ) {
  8011. matrices.push( subCamera.projectionMatrixInverse );
  8012. }
  8013. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatricesInverse' );
  8014. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrixInverse' );
  8015. } else {
  8016. cameraProjectionMatrixInverse = uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8017. }
  8018. return cameraProjectionMatrixInverse;
  8019. } ).once() )();
  8020. /**
  8021. * TSL object that represents the view matrix of the camera used for the current render.
  8022. *
  8023. * @tsl
  8024. * @type {UniformNode<mat4>}
  8025. */
  8026. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8027. let cameraViewMatrix;
  8028. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8029. const matrices = [];
  8030. for ( const subCamera of camera.cameras ) {
  8031. matrices.push( subCamera.matrixWorldInverse );
  8032. }
  8033. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  8034. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraViewMatrix' );
  8035. } else {
  8036. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8037. }
  8038. return cameraViewMatrix;
  8039. } ).once() )();
  8040. /**
  8041. * TSL object that represents the world matrix of the camera used for the current render.
  8042. *
  8043. * @tsl
  8044. * @type {UniformNode<mat4>}
  8045. */
  8046. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8047. /**
  8048. * TSL object that represents the normal matrix of the camera used for the current render.
  8049. *
  8050. * @tsl
  8051. * @type {UniformNode<mat3>}
  8052. */
  8053. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8054. /**
  8055. * TSL object that represents the position in world space of the camera used for the current render.
  8056. *
  8057. * @tsl
  8058. * @type {UniformNode<vec3>}
  8059. */
  8060. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8061. const _sphere = /*@__PURE__*/ new Sphere();
  8062. /**
  8063. * This node can be used to access transformation related metrics of 3D objects.
  8064. * Depending on the selected scope, a different metric is represented as a uniform
  8065. * in the shader. The following scopes are supported:
  8066. *
  8067. * - `POSITION`: The object's position in world space.
  8068. * - `VIEW_POSITION`: The object's position in view/camera space.
  8069. * - `DIRECTION`: The object's direction in world space.
  8070. * - `SCALE`: The object's scale in world space.
  8071. * - `WORLD_MATRIX`: The object's matrix in world space.
  8072. *
  8073. * @augments Node
  8074. */
  8075. class Object3DNode extends Node {
  8076. static get type() {
  8077. return 'Object3DNode';
  8078. }
  8079. /**
  8080. * Constructs a new object 3D node.
  8081. *
  8082. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8083. * @param {?Object3D} [object3d=null] - The 3D object.
  8084. */
  8085. constructor( scope, object3d = null ) {
  8086. super();
  8087. /**
  8088. * The node reports a different type of transformation depending on the scope.
  8089. *
  8090. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8091. */
  8092. this.scope = scope;
  8093. /**
  8094. * The 3D object.
  8095. *
  8096. * @type {?Object3D}
  8097. * @default null
  8098. */
  8099. this.object3d = object3d;
  8100. /**
  8101. * Overwritten since this type of node is updated per object.
  8102. *
  8103. * @type {string}
  8104. * @default 'object'
  8105. */
  8106. this.updateType = NodeUpdateType.OBJECT;
  8107. /**
  8108. * Holds the value of the node as a uniform.
  8109. *
  8110. * @private
  8111. * @type {UniformNode}
  8112. */
  8113. this._uniformNode = new UniformNode( null );
  8114. }
  8115. /**
  8116. * Overwritten since the node type is inferred from the scope.
  8117. *
  8118. * @return {string} The node type.
  8119. */
  8120. getNodeType() {
  8121. const scope = this.scope;
  8122. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8123. return 'mat4';
  8124. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8125. return 'vec3';
  8126. } else if ( scope === Object3DNode.RADIUS ) {
  8127. return 'float';
  8128. }
  8129. }
  8130. /**
  8131. * Updates the uniform value depending on the scope.
  8132. *
  8133. * @param {NodeFrame} frame - The current node frame.
  8134. */
  8135. update( frame ) {
  8136. const object = this.object3d;
  8137. const uniformNode = this._uniformNode;
  8138. const scope = this.scope;
  8139. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8140. uniformNode.value = object.matrixWorld;
  8141. } else if ( scope === Object3DNode.POSITION ) {
  8142. uniformNode.value = uniformNode.value || new Vector3();
  8143. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8144. } else if ( scope === Object3DNode.SCALE ) {
  8145. uniformNode.value = uniformNode.value || new Vector3();
  8146. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8147. } else if ( scope === Object3DNode.DIRECTION ) {
  8148. uniformNode.value = uniformNode.value || new Vector3();
  8149. object.getWorldDirection( uniformNode.value );
  8150. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8151. const camera = frame.camera;
  8152. uniformNode.value = uniformNode.value || new Vector3();
  8153. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8154. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8155. } else if ( scope === Object3DNode.RADIUS ) {
  8156. const geometry = frame.object.geometry;
  8157. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8158. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8159. uniformNode.value = _sphere.radius;
  8160. }
  8161. }
  8162. /**
  8163. * Generates the code snippet of the uniform node. The node type of the uniform
  8164. * node also depends on the selected scope.
  8165. *
  8166. * @param {NodeBuilder} builder - The current node builder.
  8167. * @return {string} The generated code snippet.
  8168. */
  8169. generate( builder ) {
  8170. const scope = this.scope;
  8171. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8172. this._uniformNode.nodeType = 'mat4';
  8173. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8174. this._uniformNode.nodeType = 'vec3';
  8175. } else if ( scope === Object3DNode.RADIUS ) {
  8176. this._uniformNode.nodeType = 'float';
  8177. }
  8178. return this._uniformNode.build( builder );
  8179. }
  8180. serialize( data ) {
  8181. super.serialize( data );
  8182. data.scope = this.scope;
  8183. }
  8184. deserialize( data ) {
  8185. super.deserialize( data );
  8186. this.scope = data.scope;
  8187. }
  8188. }
  8189. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8190. Object3DNode.POSITION = 'position';
  8191. Object3DNode.SCALE = 'scale';
  8192. Object3DNode.VIEW_POSITION = 'viewPosition';
  8193. Object3DNode.DIRECTION = 'direction';
  8194. Object3DNode.RADIUS = 'radius';
  8195. /**
  8196. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8197. *
  8198. * @tsl
  8199. * @function
  8200. * @param {?Object3D} [object3d] - The 3D object.
  8201. * @returns {Object3DNode<vec3>}
  8202. */
  8203. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8204. /**
  8205. * TSL function for creating an object 3D node that represents the object's world matrix.
  8206. *
  8207. * @tsl
  8208. * @function
  8209. * @param {?Object3D} [object3d] - The 3D object.
  8210. * @returns {Object3DNode<mat4>}
  8211. */
  8212. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8213. /**
  8214. * TSL function for creating an object 3D node that represents the object's position in world space.
  8215. *
  8216. * @tsl
  8217. * @function
  8218. * @param {?Object3D} [object3d] - The 3D object.
  8219. * @returns {Object3DNode<vec3>}
  8220. */
  8221. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  8222. /**
  8223. * TSL function for creating an object 3D node that represents the object's scale in world space.
  8224. *
  8225. * @tsl
  8226. * @function
  8227. * @param {?Object3D} [object3d] - The 3D object.
  8228. * @returns {Object3DNode<vec3>}
  8229. */
  8230. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  8231. /**
  8232. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  8233. *
  8234. * @tsl
  8235. * @function
  8236. * @param {?Object3D} [object3d] - The 3D object.
  8237. * @returns {Object3DNode<vec3>}
  8238. */
  8239. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  8240. /**
  8241. * TSL function for creating an object 3D node that represents the object's radius.
  8242. *
  8243. * @tsl
  8244. * @function
  8245. * @param {?Object3D} [object3d] - The 3D object.
  8246. * @returns {Object3DNode<vec3>}
  8247. */
  8248. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  8249. /**
  8250. * This type of node is a specialized version of `Object3DNode`
  8251. * with larger set of model related metrics. Unlike `Object3DNode`,
  8252. * `ModelNode` extracts the reference to the 3D object from the
  8253. * current node frame state.
  8254. *
  8255. * @augments Object3DNode
  8256. */
  8257. class ModelNode extends Object3DNode {
  8258. static get type() {
  8259. return 'ModelNode';
  8260. }
  8261. /**
  8262. * Constructs a new object model node.
  8263. *
  8264. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8265. */
  8266. constructor( scope ) {
  8267. super( scope );
  8268. }
  8269. /**
  8270. * Extracts the model reference from the frame state and then
  8271. * updates the uniform value depending on the scope.
  8272. *
  8273. * @param {NodeFrame} frame - The current node frame.
  8274. */
  8275. update( frame ) {
  8276. this.object3d = frame.object;
  8277. super.update( frame );
  8278. }
  8279. }
  8280. /**
  8281. * TSL object that represents the object's direction in world space.
  8282. *
  8283. * @tsl
  8284. * @type {ModelNode<vec3>}
  8285. */
  8286. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  8287. /**
  8288. * TSL object that represents the object's world matrix.
  8289. *
  8290. * @tsl
  8291. * @type {ModelNode<mat4>}
  8292. */
  8293. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  8294. /**
  8295. * TSL object that represents the object's position in world space.
  8296. *
  8297. * @tsl
  8298. * @type {ModelNode<vec3>}
  8299. */
  8300. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  8301. /**
  8302. * TSL object that represents the object's scale in world space.
  8303. *
  8304. * @tsl
  8305. * @type {ModelNode<vec3>}
  8306. */
  8307. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  8308. /**
  8309. * TSL object that represents the object's position in view/camera space.
  8310. *
  8311. * @tsl
  8312. * @type {ModelNode<vec3>}
  8313. */
  8314. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  8315. /**
  8316. * TSL object that represents the object's radius.
  8317. *
  8318. * @tsl
  8319. * @type {ModelNode<float>}
  8320. */
  8321. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  8322. /**
  8323. * TSL object that represents the object's normal matrix.
  8324. *
  8325. * @tsl
  8326. * @type {UniformNode<mat3>}
  8327. */
  8328. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  8329. /**
  8330. * TSL object that represents the object's inverse world matrix.
  8331. *
  8332. * @tsl
  8333. * @type {UniformNode<mat4>}
  8334. */
  8335. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  8336. /**
  8337. * TSL object that represents the object's model view matrix.
  8338. *
  8339. * @tsl
  8340. * @type {Node<mat4>}
  8341. */
  8342. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8343. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  8344. } ).once() )().toVar( 'modelViewMatrix' );
  8345. // GPU Precision
  8346. /**
  8347. * TSL object that represents the object's model view in `mediump` precision.
  8348. *
  8349. * @tsl
  8350. * @type {Node<mat4>}
  8351. */
  8352. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  8353. // CPU Precision
  8354. /**
  8355. * TSL object that represents the object's model view in `highp` precision
  8356. * which is achieved by computing the matrix in JS and not in the shader.
  8357. *
  8358. * @tsl
  8359. * @type {Node<mat4>}
  8360. */
  8361. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8362. builder.context.isHighPrecisionModelViewMatrix = true;
  8363. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  8364. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8365. } );
  8366. } ).once() )().toVar( 'highpModelViewMatrix' );
  8367. /**
  8368. * TSL object that represents the object's model normal view in `highp` precision
  8369. * which is achieved by computing the matrix in JS and not in the shader.
  8370. *
  8371. * @tsl
  8372. * @type {Node<mat3>}
  8373. */
  8374. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8375. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  8376. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  8377. if ( isHighPrecisionModelViewMatrix !== true ) {
  8378. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8379. }
  8380. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  8381. } );
  8382. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  8383. /**
  8384. * TSL object that represents the position attribute of the current rendered object.
  8385. *
  8386. * @tsl
  8387. * @type {AttributeNode<vec3>}
  8388. */
  8389. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  8390. /**
  8391. * TSL object that represents the vertex position in local space of the current rendered object.
  8392. *
  8393. * @tsl
  8394. * @type {AttributeNode<vec3>}
  8395. */
  8396. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  8397. /**
  8398. * TSL object that represents the previous vertex position in local space of the current rendered object.
  8399. * Used in context of {@link VelocityNode} for rendering motion vectors.
  8400. *
  8401. * @tsl
  8402. * @type {AttributeNode<vec3>}
  8403. */
  8404. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  8405. /**
  8406. * TSL object that represents the vertex position in world space of the current rendered object.
  8407. *
  8408. * @tsl
  8409. * @type {VaryingNode<vec3>}
  8410. */
  8411. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.toVarying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  8412. /**
  8413. * TSL object that represents the position world direction of the current rendered object.
  8414. *
  8415. * @tsl
  8416. * @type {Node<vec3>}
  8417. */
  8418. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  8419. /**
  8420. * TSL object that represents the vertex position in view space of the current rendered object.
  8421. *
  8422. * @tsl
  8423. * @type {VaryingNode<vec3>}
  8424. */
  8425. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8426. return builder.context.setupPositionView();
  8427. }, 'vec3' ).once() )().toVarying( 'v_positionView' ).context( { needsPositionReassign: true } );
  8428. /**
  8429. * TSL object that represents the position view direction of the current rendered object.
  8430. *
  8431. * @tsl
  8432. * @type {VaryingNode<vec3>}
  8433. */
  8434. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8435. /**
  8436. * This node can be used to evaluate whether a primitive is front or back facing.
  8437. *
  8438. * @augments Node
  8439. */
  8440. class FrontFacingNode extends Node {
  8441. static get type() {
  8442. return 'FrontFacingNode';
  8443. }
  8444. /**
  8445. * Constructs a new front facing node.
  8446. */
  8447. constructor() {
  8448. super( 'bool' );
  8449. /**
  8450. * This flag can be used for type testing.
  8451. *
  8452. * @type {boolean}
  8453. * @readonly
  8454. * @default true
  8455. */
  8456. this.isFrontFacingNode = true;
  8457. }
  8458. generate( builder ) {
  8459. const { renderer, material } = builder;
  8460. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8461. if ( material.side === BackSide ) {
  8462. return 'false';
  8463. }
  8464. }
  8465. return builder.getFrontFacing();
  8466. }
  8467. }
  8468. /**
  8469. * TSL object that represents whether a primitive is front or back facing
  8470. *
  8471. * @tsl
  8472. * @type {FrontFacingNode<bool>}
  8473. */
  8474. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8475. /**
  8476. * TSL object that represents the front facing status as a number instead of a bool.
  8477. * `1` means front facing, `-1` means back facing.
  8478. *
  8479. * @tsl
  8480. * @type {Node<float>}
  8481. */
  8482. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8483. /**
  8484. * TSL object that represents the normal attribute of the current rendered object.
  8485. *
  8486. * @tsl
  8487. * @type {Node<vec3>}
  8488. */
  8489. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8490. /**
  8491. * TSL object that represents the vertex normal in local space of the current rendered object.
  8492. *
  8493. * @tsl
  8494. * @type {Node<vec3>}
  8495. */
  8496. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8497. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8498. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  8499. return vec3( 0, 1, 0 );
  8500. }
  8501. return normalGeometry;
  8502. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8503. /**
  8504. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8505. *
  8506. * @tsl
  8507. * @type {Node<vec3>}
  8508. */
  8509. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8510. /**
  8511. * TSL object that represents the vertex normal in view space of the current rendered object.
  8512. *
  8513. * @tsl
  8514. * @type {Node<vec3>}
  8515. */
  8516. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8517. let node;
  8518. if ( builder.material.flatShading === true ) {
  8519. node = normalFlat;
  8520. } else {
  8521. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8522. }
  8523. return node;
  8524. }, 'vec3' ).once() )().toVar( 'normalView' );
  8525. /**
  8526. * TSL object that represents the vertex normal in world space of the current rendered object.
  8527. *
  8528. * @tsl
  8529. * @type {Node<vec3>}
  8530. */
  8531. const normalWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8532. let normal = normalView.transformDirection( cameraViewMatrix );
  8533. if ( builder.material.flatShading !== true ) {
  8534. normal = varying( normal, 'v_normalWorld' );
  8535. }
  8536. return normal;
  8537. }, 'vec3' ).once() )().normalize().toVar( 'normalWorld' );
  8538. /**
  8539. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8540. *
  8541. * @tsl
  8542. * @type {Node<vec3>}
  8543. */
  8544. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8545. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8546. let node = builder.context.setupNormal().context( { getUV: null } );
  8547. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8548. return node;
  8549. }, 'vec3' ).once() )().toVar( 'transformedNormalView' );
  8550. /**
  8551. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8552. *
  8553. * @tsl
  8554. * @type {Node<vec3>}
  8555. */
  8556. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8557. /**
  8558. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8559. *
  8560. * @tsl
  8561. * @type {Node<vec3>}
  8562. */
  8563. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8564. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8565. let node = builder.context.setupClearcoatNormal().context( { getUV: null } );
  8566. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8567. return node;
  8568. }, 'vec3' ).once() )().toVar( 'transformedClearcoatNormalView' );
  8569. /**
  8570. * Transforms the normal with the given matrix.
  8571. *
  8572. * @tsl
  8573. * @function
  8574. * @param {Node<vec3>} normal - The normal.
  8575. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8576. * @return {Node<vec3>} The transformed normal.
  8577. */
  8578. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8579. const m = mat3( matrix );
  8580. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8581. return m.mul( transformedNormal ).xyz;
  8582. } );
  8583. /**
  8584. * Transforms the given normal from local to view space.
  8585. *
  8586. * @tsl
  8587. * @function
  8588. * @param {Node<vec3>} normal - The normal.
  8589. * @param {NodeBuilder} builder - The current node builder.
  8590. * @return {Node<vec3>} The transformed normal.
  8591. */
  8592. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8593. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  8594. if ( modelNormalViewMatrix !== null ) {
  8595. return modelNormalViewMatrix.transformDirection( normal );
  8596. }
  8597. //
  8598. const transformedNormal = modelNormalMatrix.mul( normal );
  8599. return cameraViewMatrix.transformDirection( transformedNormal );
  8600. } );
  8601. const _e1$1 = /*@__PURE__*/ new Euler();
  8602. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8603. /**
  8604. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8605. *
  8606. * @tsl
  8607. * @type {UniformNode<float>}
  8608. */
  8609. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  8610. /**
  8611. * TSL object that represents the intensity of environment maps of PBR materials.
  8612. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  8613. *
  8614. * @tsl
  8615. * @type {Node<float>}
  8616. */
  8617. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  8618. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  8619. } );
  8620. /**
  8621. * TSL object that represents the rotation of environment maps.
  8622. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  8623. * rotation of `scene.environment` instead.
  8624. *
  8625. * @tsl
  8626. * @type {Node<mat4>}
  8627. */
  8628. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  8629. return frame.material;
  8630. } ).onObjectUpdate( function ( { material, scene } ) {
  8631. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  8632. if ( rotation ) {
  8633. _e1$1.copy( rotation );
  8634. _m1$1.makeRotationFromEuler( _e1$1 );
  8635. } else {
  8636. _m1$1.identity();
  8637. }
  8638. return _m1$1;
  8639. } );
  8640. /**
  8641. * The reflect vector in view space.
  8642. *
  8643. * @tsl
  8644. * @type {Node<vec3>}
  8645. */
  8646. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8647. /**
  8648. * The refract vector in view space.
  8649. *
  8650. * @tsl
  8651. * @type {Node<vec3>}
  8652. */
  8653. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8654. /**
  8655. * Used for sampling cube maps when using cube reflection mapping.
  8656. *
  8657. * @tsl
  8658. * @type {Node<vec3>}
  8659. */
  8660. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8661. /**
  8662. * Used for sampling cube maps when using cube refraction mapping.
  8663. *
  8664. * @tsl
  8665. * @type {Node<vec3>}
  8666. */
  8667. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8668. /**
  8669. * This type of uniform node represents a cube texture.
  8670. *
  8671. * @augments TextureNode
  8672. */
  8673. class CubeTextureNode extends TextureNode {
  8674. static get type() {
  8675. return 'CubeTextureNode';
  8676. }
  8677. /**
  8678. * Constructs a new cube texture node.
  8679. *
  8680. * @param {CubeTexture} value - The cube texture.
  8681. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8682. * @param {?Node<int>} [levelNode=null] - The level node.
  8683. * @param {?Node<float>} [biasNode=null] - The bias node.
  8684. */
  8685. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8686. super( value, uvNode, levelNode, biasNode );
  8687. /**
  8688. * This flag can be used for type testing.
  8689. *
  8690. * @type {boolean}
  8691. * @readonly
  8692. * @default true
  8693. */
  8694. this.isCubeTextureNode = true;
  8695. }
  8696. /**
  8697. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8698. *
  8699. * @param {NodeBuilder} builder - The current node builder.
  8700. * @return {string} The input type.
  8701. */
  8702. getInputType( /*builder*/ ) {
  8703. return 'cubeTexture';
  8704. }
  8705. /**
  8706. * Returns a default uvs based on the mapping type of the cube texture.
  8707. *
  8708. * @return {Node<vec3>} The default uv attribute.
  8709. */
  8710. getDefaultUV() {
  8711. const texture = this.value;
  8712. if ( texture.mapping === CubeReflectionMapping ) {
  8713. return reflectVector;
  8714. } else if ( texture.mapping === CubeRefractionMapping ) {
  8715. return refractVector;
  8716. } else {
  8717. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8718. return vec3( 0, 0, 0 );
  8719. }
  8720. }
  8721. /**
  8722. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8723. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8724. *
  8725. * @param {boolean} value - The update toggle.
  8726. */
  8727. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8728. /**
  8729. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8730. * to modify the uv node for correct sampling.
  8731. *
  8732. * @param {NodeBuilder} builder - The current node builder.
  8733. * @param {Node} uvNode - The uv node to setup.
  8734. * @return {Node} The updated uv node.
  8735. */
  8736. setupUV( builder, uvNode ) {
  8737. const texture = this.value;
  8738. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8739. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8740. }
  8741. return materialEnvRotation.mul( uvNode );
  8742. }
  8743. /**
  8744. * Generates the uv code snippet.
  8745. *
  8746. * @param {NodeBuilder} builder - The current node builder.
  8747. * @param {Node} cubeUV - The uv node to generate code for.
  8748. * @return {string} The generated code snippet.
  8749. */
  8750. generateUV( builder, cubeUV ) {
  8751. return cubeUV.build( builder, 'vec3' );
  8752. }
  8753. }
  8754. /**
  8755. * TSL function for creating a cube texture node.
  8756. *
  8757. * @tsl
  8758. * @function
  8759. * @param {CubeTexture} value - The cube texture.
  8760. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8761. * @param {?Node<int>} [levelNode=null] - The level node.
  8762. * @param {?Node<float>} [biasNode=null] - The bias node.
  8763. * @returns {CubeTextureNode}
  8764. */
  8765. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  8766. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8767. /**
  8768. * This class is only relevant if the referenced property is array-like.
  8769. * In this case, `ReferenceElementNode` allows to refer to a specific
  8770. * element inside the data structure via an index.
  8771. *
  8772. * @augments ArrayElementNode
  8773. */
  8774. class ReferenceElementNode extends ArrayElementNode {
  8775. static get type() {
  8776. return 'ReferenceElementNode';
  8777. }
  8778. /**
  8779. * Constructs a new reference element node.
  8780. *
  8781. * @param {?ReferenceNode} referenceNode - The reference node.
  8782. * @param {Node} indexNode - The index node that defines the element access.
  8783. */
  8784. constructor( referenceNode, indexNode ) {
  8785. super( referenceNode, indexNode );
  8786. /**
  8787. * Similar to {@link ReferenceNode#reference}, an additional
  8788. * property references to the current node.
  8789. *
  8790. * @type {?ReferenceNode}
  8791. * @default null
  8792. */
  8793. this.referenceNode = referenceNode;
  8794. /**
  8795. * This flag can be used for type testing.
  8796. *
  8797. * @type {boolean}
  8798. * @readonly
  8799. * @default true
  8800. */
  8801. this.isReferenceElementNode = true;
  8802. }
  8803. /**
  8804. * This method is overwritten since the node type is inferred from
  8805. * the uniform type of the reference node.
  8806. *
  8807. * @return {string} The node type.
  8808. */
  8809. getNodeType() {
  8810. return this.referenceNode.uniformType;
  8811. }
  8812. generate( builder ) {
  8813. const snippet = super.generate( builder );
  8814. const arrayType = this.referenceNode.getNodeType();
  8815. const elementType = this.getNodeType();
  8816. return builder.format( snippet, arrayType, elementType );
  8817. }
  8818. }
  8819. /**
  8820. * This type of node establishes a reference to a property of another object.
  8821. * In this way, the value of the node is automatically linked to the value of
  8822. * referenced object. Reference nodes internally represent the linked value
  8823. * as a uniform.
  8824. *
  8825. * @augments Node
  8826. */
  8827. class ReferenceNode extends Node {
  8828. static get type() {
  8829. return 'ReferenceNode';
  8830. }
  8831. /**
  8832. * Constructs a new reference node.
  8833. *
  8834. * @param {string} property - The name of the property the node refers to.
  8835. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  8836. * @param {?Object} [object=null] - The object the property belongs to.
  8837. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  8838. */
  8839. constructor( property, uniformType, object = null, count = null ) {
  8840. super();
  8841. /**
  8842. * The name of the property the node refers to.
  8843. *
  8844. * @type {string}
  8845. */
  8846. this.property = property;
  8847. /**
  8848. * The uniform type that should be used to represent the property value.
  8849. *
  8850. * @type {string}
  8851. */
  8852. this.uniformType = uniformType;
  8853. /**
  8854. * The object the property belongs to.
  8855. *
  8856. * @type {?Object}
  8857. * @default null
  8858. */
  8859. this.object = object;
  8860. /**
  8861. * When the linked property is an array, this parameter defines its length.
  8862. *
  8863. * @type {?number}
  8864. * @default null
  8865. */
  8866. this.count = count;
  8867. /**
  8868. * The property name might have dots so nested properties can be referred.
  8869. * The hierarchy of the names is stored inside this array.
  8870. *
  8871. * @type {Array<string>}
  8872. */
  8873. this.properties = property.split( '.' );
  8874. /**
  8875. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  8876. * since the final reference might be updated from calling code.
  8877. *
  8878. * @type {?Object}
  8879. * @default null
  8880. */
  8881. this.reference = object;
  8882. /**
  8883. * The uniform node that holds the value of the reference node.
  8884. *
  8885. * @type {UniformNode}
  8886. * @default null
  8887. */
  8888. this.node = null;
  8889. /**
  8890. * The uniform group of the internal uniform.
  8891. *
  8892. * @type {UniformGroupNode}
  8893. * @default null
  8894. */
  8895. this.group = null;
  8896. /**
  8897. * An optional label of the internal uniform node.
  8898. *
  8899. * @type {?string}
  8900. * @default null
  8901. */
  8902. this.name = null;
  8903. /**
  8904. * Overwritten since reference nodes are updated per object.
  8905. *
  8906. * @type {string}
  8907. * @default 'object'
  8908. */
  8909. this.updateType = NodeUpdateType.OBJECT;
  8910. }
  8911. /**
  8912. * When the referred property is array-like, this method can be used
  8913. * to access elements via an index node.
  8914. *
  8915. * @param {IndexNode} indexNode - indexNode.
  8916. * @return {ReferenceElementNode} A reference to an element.
  8917. */
  8918. element( indexNode ) {
  8919. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8920. }
  8921. /**
  8922. * Sets the uniform group for this reference node.
  8923. *
  8924. * @param {UniformGroupNode} group - The uniform group to set.
  8925. * @return {ReferenceNode} A reference to this node.
  8926. */
  8927. setGroup( group ) {
  8928. this.group = group;
  8929. return this;
  8930. }
  8931. /**
  8932. * Sets the label for the internal uniform.
  8933. *
  8934. * @param {string} name - The label to set.
  8935. * @return {ReferenceNode} A reference to this node.
  8936. */
  8937. label( name ) {
  8938. this.name = name;
  8939. return this;
  8940. }
  8941. /**
  8942. * Sets the node type which automatically defines the internal
  8943. * uniform type.
  8944. *
  8945. * @param {string} uniformType - The type to set.
  8946. */
  8947. setNodeType( uniformType ) {
  8948. let node = null;
  8949. if ( this.count !== null ) {
  8950. node = buffer( null, uniformType, this.count );
  8951. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8952. node = uniformArray( null, uniformType );
  8953. } else if ( uniformType === 'texture' ) {
  8954. node = texture( null );
  8955. } else if ( uniformType === 'cubeTexture' ) {
  8956. node = cubeTexture( null );
  8957. } else {
  8958. node = uniform( null, uniformType );
  8959. }
  8960. if ( this.group !== null ) {
  8961. node.setGroup( this.group );
  8962. }
  8963. if ( this.name !== null ) node.label( this.name );
  8964. this.node = node.getSelf();
  8965. }
  8966. /**
  8967. * This method is overwritten since the node type is inferred from
  8968. * the type of the reference node.
  8969. *
  8970. * @param {NodeBuilder} builder - The current node builder.
  8971. * @return {string} The node type.
  8972. */
  8973. getNodeType( builder ) {
  8974. if ( this.node === null ) {
  8975. this.updateReference( builder );
  8976. this.updateValue();
  8977. }
  8978. return this.node.getNodeType( builder );
  8979. }
  8980. /**
  8981. * Returns the property value from the given referred object.
  8982. *
  8983. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8984. * @return {any} The value.
  8985. */
  8986. getValueFromReference( object = this.reference ) {
  8987. const { properties } = this;
  8988. let value = object[ properties[ 0 ] ];
  8989. for ( let i = 1; i < properties.length; i ++ ) {
  8990. value = value[ properties[ i ] ];
  8991. }
  8992. return value;
  8993. }
  8994. /**
  8995. * Allows to update the reference based on the given state. The state is only
  8996. * evaluated {@link ReferenceNode#object} is not set.
  8997. *
  8998. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8999. * @return {Object} The updated reference.
  9000. */
  9001. updateReference( state ) {
  9002. this.reference = this.object !== null ? this.object : state.object;
  9003. return this.reference;
  9004. }
  9005. /**
  9006. * The output of the reference node is the internal uniform node.
  9007. *
  9008. * @param {NodeBuilder} builder - The current node builder.
  9009. * @return {UniformNode} The output node.
  9010. */
  9011. setup( /* builder */ ) {
  9012. this.updateValue();
  9013. return this.node;
  9014. }
  9015. /**
  9016. * Overwritten to update the internal uniform value.
  9017. *
  9018. * @param {NodeFrame} frame - A reference to the current node frame.
  9019. */
  9020. update( /*frame*/ ) {
  9021. this.updateValue();
  9022. }
  9023. /**
  9024. * Retrieves the value from the referred object property and uses it
  9025. * to updated the internal uniform.
  9026. */
  9027. updateValue() {
  9028. if ( this.node === null ) this.setNodeType( this.uniformType );
  9029. const value = this.getValueFromReference();
  9030. if ( Array.isArray( value ) ) {
  9031. this.node.array = value;
  9032. } else {
  9033. this.node.value = value;
  9034. }
  9035. }
  9036. }
  9037. /**
  9038. * TSL function for creating a reference node.
  9039. *
  9040. * @tsl
  9041. * @function
  9042. * @param {string} name - The name of the property the node refers to.
  9043. * @param {string} type - The uniform type that should be used to represent the property value.
  9044. * @param {?Object} [object] - The object the property belongs to.
  9045. * @returns {ReferenceNode}
  9046. */
  9047. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9048. /**
  9049. * TSL function for creating a reference node. Use this function if you want need a reference
  9050. * to an array-like property that should be represented as a uniform buffer.
  9051. *
  9052. * @tsl
  9053. * @function
  9054. * @param {string} name - The name of the property the node refers to.
  9055. * @param {string} type - The uniform type that should be used to represent the property value.
  9056. * @param {number} count - The number of value inside the array-like object.
  9057. * @param {Object} object - An array-like object the property belongs to.
  9058. * @returns {ReferenceNode}
  9059. */
  9060. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9061. /**
  9062. * This node is a special type of reference node which is intended
  9063. * for linking material properties with node values.
  9064. * ```js
  9065. * const opacityNode = materialReference( 'opacity', 'float', material );
  9066. * ```
  9067. * When changing `material.opacity`, the node value of `opacityNode` will
  9068. * automatically be updated.
  9069. *
  9070. * @augments ReferenceNode
  9071. */
  9072. class MaterialReferenceNode extends ReferenceNode {
  9073. static get type() {
  9074. return 'MaterialReferenceNode';
  9075. }
  9076. /**
  9077. * Constructs a new material reference node.
  9078. *
  9079. * @param {string} property - The name of the property the node refers to.
  9080. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9081. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9082. * the node refers to the material of the current rendered object.
  9083. */
  9084. constructor( property, inputType, material = null ) {
  9085. super( property, inputType, material );
  9086. /**
  9087. * The material the property belongs to. When no material is set,
  9088. * the node refers to the material of the current rendered object.
  9089. *
  9090. * @type {?Material}
  9091. * @default null
  9092. */
  9093. this.material = material;
  9094. /**
  9095. * This flag can be used for type testing.
  9096. *
  9097. * @type {boolean}
  9098. * @readonly
  9099. * @default true
  9100. */
  9101. this.isMaterialReferenceNode = true;
  9102. }
  9103. /**
  9104. * Updates the reference based on the given state. The state is only evaluated
  9105. * {@link MaterialReferenceNode#material} is not set.
  9106. *
  9107. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9108. * @return {Object} The updated reference.
  9109. */
  9110. updateReference( state ) {
  9111. this.reference = this.material !== null ? this.material : state.material;
  9112. return this.reference;
  9113. }
  9114. }
  9115. /**
  9116. * TSL function for creating a material reference node.
  9117. *
  9118. * @tsl
  9119. * @function
  9120. * @param {string} name - The name of the property the node refers to.
  9121. * @param {string} type - The uniform type that should be used to represent the property value.
  9122. * @param {?Material} [material=null] - The material the property belongs to.
  9123. * When no material is set, the node refers to the material of the current rendered object.
  9124. * @returns {MaterialReferenceNode}
  9125. */
  9126. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  9127. /**
  9128. * TSL object that represents the tangent attribute of the current rendered object.
  9129. *
  9130. * @tsl
  9131. * @type {Node<vec4>}
  9132. */
  9133. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  9134. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  9135. builder.geometry.computeTangents();
  9136. }
  9137. return attribute( 'tangent', 'vec4' );
  9138. } )();
  9139. /**
  9140. * TSL object that represents the vertex tangent in local space of the current rendered object.
  9141. *
  9142. * @tsl
  9143. * @type {Node<vec3>}
  9144. */
  9145. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  9146. /**
  9147. * TSL object that represents the vertex tangent in view space of the current rendered object.
  9148. *
  9149. * @tsl
  9150. * @type {Node<vec3>}
  9151. */
  9152. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  9153. /**
  9154. * TSL object that represents the vertex tangent in world space of the current rendered object.
  9155. *
  9156. * @tsl
  9157. * @type {Node<vec3>}
  9158. */
  9159. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  9160. /**
  9161. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  9162. *
  9163. * @tsl
  9164. * @type {Node<vec3>}
  9165. */
  9166. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  9167. /**
  9168. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  9169. *
  9170. * @tsl
  9171. * @type {Node<vec3>}
  9172. */
  9173. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  9174. /**
  9175. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  9176. *
  9177. * @tsl
  9178. * @private
  9179. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  9180. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  9181. * @returns {Node<vec3>} The bitangent node.
  9182. */
  9183. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  9184. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  9185. if ( builder.material.flatShading !== true ) {
  9186. bitangent = varying( crossNormalTangent, varyingName );
  9187. }
  9188. return bitangent;
  9189. } ).once();
  9190. /**
  9191. * TSL object that represents the bitangent attribute of the current rendered object.
  9192. *
  9193. * @tsl
  9194. * @type {Node<vec3>}
  9195. */
  9196. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  9197. /**
  9198. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  9199. *
  9200. * @tsl
  9201. * @type {Node<vec3>}
  9202. */
  9203. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  9204. /**
  9205. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  9206. *
  9207. * @tsl
  9208. * @type {Node<vec3>}
  9209. */
  9210. const bitangentView = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  9211. /**
  9212. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  9213. *
  9214. * @tsl
  9215. * @type {Node<vec3>}
  9216. */
  9217. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  9218. /**
  9219. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  9220. *
  9221. * @tsl
  9222. * @type {Node<vec3>}
  9223. */
  9224. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ), 'v_transformedBitangentView' ).normalize().toVar( 'transformedBitangentView' );
  9225. /**
  9226. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  9227. *
  9228. * @tsl
  9229. * @type {Node<vec4>}
  9230. */
  9231. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  9232. /**
  9233. * TSL object that represents the TBN matrix in view space.
  9234. *
  9235. * @tsl
  9236. * @type {Node<mat3>}
  9237. */
  9238. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  9239. /**
  9240. * TSL object that represents the parallax direction.
  9241. *
  9242. * @tsl
  9243. * @type {Node<mat3>}
  9244. */
  9245. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  9246. /**
  9247. * TSL function for computing parallax uv coordinates.
  9248. *
  9249. * @tsl
  9250. * @function
  9251. * @param {Node<vec2>} uv - A uv node.
  9252. * @param {Node<vec2>} scale - A scale node.
  9253. * @returns {Node<vec2>} Parallax uv coordinates.
  9254. */
  9255. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  9256. /**
  9257. * TSL function for computing bent normals.
  9258. *
  9259. * @tsl
  9260. * @function
  9261. * @returns {Node<vec3>} Bent normals.
  9262. */
  9263. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  9264. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  9265. let bentNormal = anisotropyB.cross( positionViewDirection );
  9266. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  9267. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  9268. return bentNormal;
  9269. } )();
  9270. // Normal Mapping Without Precomputed Tangents
  9271. // http://www.thetenthplanet.de/archives/1180
  9272. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  9273. const { eye_pos, surf_norm, mapN, uv } = inputs;
  9274. const q0 = eye_pos.dFdx();
  9275. const q1 = eye_pos.dFdy();
  9276. const st0 = uv.dFdx();
  9277. const st1 = uv.dFdy();
  9278. const N = surf_norm; // normalized
  9279. const q1perp = q1.cross( N );
  9280. const q0perp = N.cross( q0 );
  9281. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  9282. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  9283. const det = T.dot( T ).max( B.dot( B ) );
  9284. const scale = faceDirection.mul( det.inverseSqrt() );
  9285. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  9286. } );
  9287. /**
  9288. * This class can be used for applying normals maps to materials.
  9289. *
  9290. * ```js
  9291. * material.normalNode = normalMap( texture( normalTex ) );
  9292. * ```
  9293. *
  9294. * @augments TempNode
  9295. */
  9296. class NormalMapNode extends TempNode {
  9297. static get type() {
  9298. return 'NormalMapNode';
  9299. }
  9300. /**
  9301. * Constructs a new normal map node.
  9302. *
  9303. * @param {Node<vec3>} node - Represents the normal map data.
  9304. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9305. */
  9306. constructor( node, scaleNode = null ) {
  9307. super( 'vec3' );
  9308. /**
  9309. * Represents the normal map data.
  9310. *
  9311. * @type {Node<vec3>}
  9312. */
  9313. this.node = node;
  9314. /**
  9315. * Controls the intensity of the effect.
  9316. *
  9317. * @type {?Node<vec2>}
  9318. * @default null
  9319. */
  9320. this.scaleNode = scaleNode;
  9321. /**
  9322. * The normal map type.
  9323. *
  9324. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  9325. * @default TangentSpaceNormalMap
  9326. */
  9327. this.normalMapType = TangentSpaceNormalMap;
  9328. }
  9329. setup( builder ) {
  9330. const { normalMapType, scaleNode } = this;
  9331. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  9332. if ( scaleNode !== null ) {
  9333. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  9334. }
  9335. let outputNode = null;
  9336. if ( normalMapType === ObjectSpaceNormalMap ) {
  9337. outputNode = transformNormalToView( normalMap );
  9338. } else if ( normalMapType === TangentSpaceNormalMap ) {
  9339. const tangent = builder.hasGeometryAttribute( 'tangent' );
  9340. if ( tangent === true ) {
  9341. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  9342. } else {
  9343. outputNode = perturbNormal2Arb( {
  9344. eye_pos: positionView,
  9345. surf_norm: normalView,
  9346. mapN: normalMap,
  9347. uv: uv()
  9348. } );
  9349. }
  9350. }
  9351. return outputNode;
  9352. }
  9353. }
  9354. /**
  9355. * TSL function for creating a normal map node.
  9356. *
  9357. * @tsl
  9358. * @function
  9359. * @param {Node<vec3>} node - Represents the normal map data.
  9360. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9361. * @returns {NormalMapNode}
  9362. */
  9363. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  9364. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9365. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  9366. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  9367. // It's used to preserve the same TextureNode instance
  9368. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  9369. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  9370. return vec2(
  9371. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  9372. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  9373. ).mul( bumpScale );
  9374. } );
  9375. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9376. const perturbNormalArb = Fn( ( inputs ) => {
  9377. const { surf_pos, surf_norm, dHdxy } = inputs;
  9378. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  9379. const vSigmaX = surf_pos.dFdx().normalize();
  9380. const vSigmaY = surf_pos.dFdy().normalize();
  9381. const vN = surf_norm; // normalized
  9382. const R1 = vSigmaY.cross( vN );
  9383. const R2 = vN.cross( vSigmaX );
  9384. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  9385. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  9386. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  9387. } );
  9388. /**
  9389. * This class can be used for applying bump maps to materials.
  9390. *
  9391. * ```js
  9392. * material.normalNode = bumpMap( texture( bumpTex ) );
  9393. * ```
  9394. *
  9395. * @augments TempNode
  9396. */
  9397. class BumpMapNode extends TempNode {
  9398. static get type() {
  9399. return 'BumpMapNode';
  9400. }
  9401. /**
  9402. * Constructs a new bump map node.
  9403. *
  9404. * @param {Node<float>} textureNode - Represents the bump map data.
  9405. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9406. */
  9407. constructor( textureNode, scaleNode = null ) {
  9408. super( 'vec3' );
  9409. /**
  9410. * Represents the bump map data.
  9411. *
  9412. * @type {Node<float>}
  9413. */
  9414. this.textureNode = textureNode;
  9415. /**
  9416. * Controls the intensity of the bump effect.
  9417. *
  9418. * @type {?Node<float>}
  9419. * @default null
  9420. */
  9421. this.scaleNode = scaleNode;
  9422. }
  9423. setup() {
  9424. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  9425. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  9426. return perturbNormalArb( {
  9427. surf_pos: positionView,
  9428. surf_norm: normalView,
  9429. dHdxy
  9430. } );
  9431. }
  9432. }
  9433. /**
  9434. * TSL function for creating a bump map node.
  9435. *
  9436. * @tsl
  9437. * @function
  9438. * @param {Node<float>} textureNode - Represents the bump map data.
  9439. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9440. * @returns {BumpMapNode}
  9441. */
  9442. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  9443. const _propertyCache = new Map();
  9444. /**
  9445. * This class should simplify the node access to material properties.
  9446. * It internal uses reference nodes to make sure changes to material
  9447. * properties are automatically reflected to predefined TSL objects
  9448. * like e.g. `materialColor`.
  9449. *
  9450. * @augments Node
  9451. */
  9452. class MaterialNode extends Node {
  9453. static get type() {
  9454. return 'MaterialNode';
  9455. }
  9456. /**
  9457. * Constructs a new material node.
  9458. *
  9459. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9460. */
  9461. constructor( scope ) {
  9462. super();
  9463. /**
  9464. * The scope defines what material property is referred by the node.
  9465. *
  9466. * @type {string}
  9467. */
  9468. this.scope = scope;
  9469. }
  9470. /**
  9471. * Returns a cached reference node for the given property and type.
  9472. *
  9473. * @param {string} property - The name of the material property.
  9474. * @param {string} type - The uniform type of the property.
  9475. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9476. */
  9477. getCache( property, type ) {
  9478. let node = _propertyCache.get( property );
  9479. if ( node === undefined ) {
  9480. node = materialReference( property, type );
  9481. _propertyCache.set( property, node );
  9482. }
  9483. return node;
  9484. }
  9485. /**
  9486. * Returns a float-typed material reference node for the given property name.
  9487. *
  9488. * @param {string} property - The name of the material property.
  9489. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  9490. */
  9491. getFloat( property ) {
  9492. return this.getCache( property, 'float' );
  9493. }
  9494. /**
  9495. * Returns a color-typed material reference node for the given property name.
  9496. *
  9497. * @param {string} property - The name of the material property.
  9498. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  9499. */
  9500. getColor( property ) {
  9501. return this.getCache( property, 'color' );
  9502. }
  9503. /**
  9504. * Returns a texture-typed material reference node for the given property name.
  9505. *
  9506. * @param {string} property - The name of the material property.
  9507. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9508. */
  9509. getTexture( property ) {
  9510. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  9511. }
  9512. /**
  9513. * The node setup is done depending on the selected scope. Multiple material properties
  9514. * might be grouped into a single node composition if they logically belong together.
  9515. *
  9516. * @param {NodeBuilder} builder - The current node builder.
  9517. * @return {Node} The node representing the selected scope.
  9518. */
  9519. setup( builder ) {
  9520. const material = builder.context.material;
  9521. const scope = this.scope;
  9522. let node = null;
  9523. if ( scope === MaterialNode.COLOR ) {
  9524. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  9525. if ( material.map && material.map.isTexture === true ) {
  9526. node = colorNode.mul( this.getTexture( 'map' ) );
  9527. } else {
  9528. node = colorNode;
  9529. }
  9530. } else if ( scope === MaterialNode.OPACITY ) {
  9531. const opacityNode = this.getFloat( scope );
  9532. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9533. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9534. } else {
  9535. node = opacityNode;
  9536. }
  9537. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9538. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9539. node = this.getTexture( 'specular' ).r;
  9540. } else {
  9541. node = float( 1 );
  9542. }
  9543. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9544. const specularIntensityNode = this.getFloat( scope );
  9545. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9546. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9547. } else {
  9548. node = specularIntensityNode;
  9549. }
  9550. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9551. const specularColorNode = this.getColor( scope );
  9552. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9553. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9554. } else {
  9555. node = specularColorNode;
  9556. }
  9557. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9558. const roughnessNode = this.getFloat( scope );
  9559. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9560. node = roughnessNode.mul( this.getTexture( scope ).g );
  9561. } else {
  9562. node = roughnessNode;
  9563. }
  9564. } else if ( scope === MaterialNode.METALNESS ) {
  9565. const metalnessNode = this.getFloat( scope );
  9566. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9567. node = metalnessNode.mul( this.getTexture( scope ).b );
  9568. } else {
  9569. node = metalnessNode;
  9570. }
  9571. } else if ( scope === MaterialNode.EMISSIVE ) {
  9572. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9573. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9574. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9575. node = emissiveNode.mul( this.getTexture( scope ) );
  9576. } else {
  9577. node = emissiveNode;
  9578. }
  9579. } else if ( scope === MaterialNode.NORMAL ) {
  9580. if ( material.normalMap ) {
  9581. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9582. node.normalMapType = material.normalMapType;
  9583. } else if ( material.bumpMap ) {
  9584. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9585. } else {
  9586. node = normalView;
  9587. }
  9588. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9589. const clearcoatNode = this.getFloat( scope );
  9590. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9591. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9592. } else {
  9593. node = clearcoatNode;
  9594. }
  9595. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9596. const clearcoatRoughnessNode = this.getFloat( scope );
  9597. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9598. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9599. } else {
  9600. node = clearcoatRoughnessNode;
  9601. }
  9602. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9603. if ( material.clearcoatNormalMap ) {
  9604. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9605. } else {
  9606. node = normalView;
  9607. }
  9608. } else if ( scope === MaterialNode.SHEEN ) {
  9609. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9610. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9611. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9612. } else {
  9613. node = sheenNode;
  9614. }
  9615. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9616. const sheenRoughnessNode = this.getFloat( scope );
  9617. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9618. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9619. } else {
  9620. node = sheenRoughnessNode;
  9621. }
  9622. node = node.clamp( 0.07, 1.0 );
  9623. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9624. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9625. const anisotropyPolar = this.getTexture( scope );
  9626. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9627. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9628. } else {
  9629. node = materialAnisotropyVector;
  9630. }
  9631. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9632. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9633. if ( material.iridescenceThicknessMap ) {
  9634. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9635. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9636. } else {
  9637. node = iridescenceThicknessMaximum;
  9638. }
  9639. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9640. const transmissionNode = this.getFloat( scope );
  9641. if ( material.transmissionMap ) {
  9642. node = transmissionNode.mul( this.getTexture( scope ).r );
  9643. } else {
  9644. node = transmissionNode;
  9645. }
  9646. } else if ( scope === MaterialNode.THICKNESS ) {
  9647. const thicknessNode = this.getFloat( scope );
  9648. if ( material.thicknessMap ) {
  9649. node = thicknessNode.mul( this.getTexture( scope ).g );
  9650. } else {
  9651. node = thicknessNode;
  9652. }
  9653. } else if ( scope === MaterialNode.IOR ) {
  9654. node = this.getFloat( scope );
  9655. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9656. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9657. } else if ( scope === MaterialNode.AO ) {
  9658. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9659. } else {
  9660. const outputType = this.getNodeType( builder );
  9661. node = this.getCache( scope, outputType );
  9662. }
  9663. return node;
  9664. }
  9665. }
  9666. MaterialNode.ALPHA_TEST = 'alphaTest';
  9667. MaterialNode.COLOR = 'color';
  9668. MaterialNode.OPACITY = 'opacity';
  9669. MaterialNode.SHININESS = 'shininess';
  9670. MaterialNode.SPECULAR = 'specular';
  9671. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9672. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9673. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9674. MaterialNode.REFLECTIVITY = 'reflectivity';
  9675. MaterialNode.ROUGHNESS = 'roughness';
  9676. MaterialNode.METALNESS = 'metalness';
  9677. MaterialNode.NORMAL = 'normal';
  9678. MaterialNode.CLEARCOAT = 'clearcoat';
  9679. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9680. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9681. MaterialNode.EMISSIVE = 'emissive';
  9682. MaterialNode.ROTATION = 'rotation';
  9683. MaterialNode.SHEEN = 'sheen';
  9684. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9685. MaterialNode.ANISOTROPY = 'anisotropy';
  9686. MaterialNode.IRIDESCENCE = 'iridescence';
  9687. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9688. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9689. MaterialNode.IOR = 'ior';
  9690. MaterialNode.TRANSMISSION = 'transmission';
  9691. MaterialNode.THICKNESS = 'thickness';
  9692. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9693. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9694. MaterialNode.LINE_SCALE = 'scale';
  9695. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9696. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9697. MaterialNode.LINE_WIDTH = 'linewidth';
  9698. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9699. MaterialNode.POINT_SIZE = 'size';
  9700. MaterialNode.DISPERSION = 'dispersion';
  9701. MaterialNode.LIGHT_MAP = 'light';
  9702. MaterialNode.AO = 'ao';
  9703. /**
  9704. * TSL object that represents alpha test of the current material.
  9705. *
  9706. * @tsl
  9707. * @type {Node<float>}
  9708. */
  9709. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9710. /**
  9711. * TSL object that represents the diffuse color of the current material.
  9712. * The value is composed via `color` * `map`.
  9713. *
  9714. * @tsl
  9715. * @type {Node<vec3>}
  9716. */
  9717. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9718. /**
  9719. * TSL object that represents the shininess of the current material.
  9720. *
  9721. * @tsl
  9722. * @type {Node<float>}
  9723. */
  9724. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9725. /**
  9726. * TSL object that represents the emissive color of the current material.
  9727. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9728. *
  9729. * @tsl
  9730. * @type {Node<vec3>}
  9731. */
  9732. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9733. /**
  9734. * TSL object that represents the opacity of the current material.
  9735. * The value is composed via `opacity` * `alphaMap`.
  9736. *
  9737. * @tsl
  9738. * @type {Node<float>}
  9739. */
  9740. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9741. /**
  9742. * TSL object that represents the specular of the current material.
  9743. *
  9744. * @tsl
  9745. * @type {Node<vec3>}
  9746. */
  9747. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9748. /**
  9749. * TSL object that represents the specular intensity of the current material.
  9750. * The value is composed via `specularIntensity` * `specularMap.a`.
  9751. *
  9752. * @tsl
  9753. * @type {Node<float>}
  9754. */
  9755. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9756. /**
  9757. * TSL object that represents the specular color of the current material.
  9758. * The value is composed via `specularColor` * `specularMap.rgb`.
  9759. *
  9760. * @tsl
  9761. * @type {Node<vec3>}
  9762. */
  9763. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9764. /**
  9765. * TSL object that represents the specular strength of the current material.
  9766. * The value is composed via `specularMap.r`.
  9767. *
  9768. * @tsl
  9769. * @type {Node<float>}
  9770. */
  9771. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9772. /**
  9773. * TSL object that represents the reflectivity of the current material.
  9774. *
  9775. * @tsl
  9776. * @type {Node<float>}
  9777. */
  9778. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9779. /**
  9780. * TSL object that represents the roughness of the current material.
  9781. * The value is composed via `roughness` * `roughnessMap.g`.
  9782. *
  9783. * @tsl
  9784. * @type {Node<float>}
  9785. */
  9786. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9787. /**
  9788. * TSL object that represents the metalness of the current material.
  9789. * The value is composed via `metalness` * `metalnessMap.b`.
  9790. *
  9791. * @tsl
  9792. * @type {Node<float>}
  9793. */
  9794. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9795. /**
  9796. * TSL object that represents the normal of the current material.
  9797. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9798. *
  9799. * @tsl
  9800. * @type {Node<vec3>}
  9801. */
  9802. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9803. /**
  9804. * TSL object that represents the clearcoat of the current material.
  9805. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9806. *
  9807. * @tsl
  9808. * @type {Node<float>}
  9809. */
  9810. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9811. /**
  9812. * TSL object that represents the clearcoat roughness of the current material.
  9813. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9814. *
  9815. * @tsl
  9816. * @type {Node<float>}
  9817. */
  9818. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9819. /**
  9820. * TSL object that represents the clearcoat normal of the current material.
  9821. * The value will be either `clearcoatNormalMap` or `normalView`.
  9822. *
  9823. * @tsl
  9824. * @type {Node<vec3>}
  9825. */
  9826. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  9827. /**
  9828. * TSL object that represents the rotation of the current sprite material.
  9829. *
  9830. * @tsl
  9831. * @type {Node<float>}
  9832. */
  9833. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  9834. /**
  9835. * TSL object that represents the sheen color of the current material.
  9836. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  9837. *
  9838. * @tsl
  9839. * @type {Node<vec3>}
  9840. */
  9841. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  9842. /**
  9843. * TSL object that represents the sheen roughness of the current material.
  9844. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  9845. *
  9846. * @tsl
  9847. * @type {Node<float>}
  9848. */
  9849. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  9850. /**
  9851. * TSL object that represents the anisotropy of the current material.
  9852. *
  9853. * @tsl
  9854. * @type {Node<vec2>}
  9855. */
  9856. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  9857. /**
  9858. * TSL object that represents the iridescence of the current material.
  9859. *
  9860. * @tsl
  9861. * @type {Node<float>}
  9862. */
  9863. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  9864. /**
  9865. * TSL object that represents the iridescence IOR of the current material.
  9866. *
  9867. * @tsl
  9868. * @type {Node<float>}
  9869. */
  9870. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  9871. /**
  9872. * TSL object that represents the iridescence thickness of the current material.
  9873. *
  9874. * @tsl
  9875. * @type {Node<float>}
  9876. */
  9877. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  9878. /**
  9879. * TSL object that represents the transmission of the current material.
  9880. * The value is composed via `transmission` * `transmissionMap.r`.
  9881. *
  9882. * @tsl
  9883. * @type {Node<float>}
  9884. */
  9885. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  9886. /**
  9887. * TSL object that represents the thickness of the current material.
  9888. * The value is composed via `thickness` * `thicknessMap.g`.
  9889. *
  9890. * @tsl
  9891. * @type {Node<float>}
  9892. */
  9893. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  9894. /**
  9895. * TSL object that represents the IOR of the current material.
  9896. *
  9897. * @tsl
  9898. * @type {Node<float>}
  9899. */
  9900. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  9901. /**
  9902. * TSL object that represents the attenuation distance of the current material.
  9903. *
  9904. * @tsl
  9905. * @type {Node<float>}
  9906. */
  9907. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  9908. /**
  9909. * TSL object that represents the attenuation color of the current material.
  9910. *
  9911. * @tsl
  9912. * @type {Node<vec3>}
  9913. */
  9914. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  9915. /**
  9916. * TSL object that represents the scale of the current dashed line material.
  9917. *
  9918. * @tsl
  9919. * @type {Node<float>}
  9920. */
  9921. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  9922. /**
  9923. * TSL object that represents the dash size of the current dashed line material.
  9924. *
  9925. * @tsl
  9926. * @type {Node<float>}
  9927. */
  9928. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  9929. /**
  9930. * TSL object that represents the gap size of the current dashed line material.
  9931. *
  9932. * @tsl
  9933. * @type {Node<float>}
  9934. */
  9935. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  9936. /**
  9937. * TSL object that represents the line width of the current line material.
  9938. *
  9939. * @tsl
  9940. * @type {Node<float>}
  9941. */
  9942. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  9943. /**
  9944. * TSL object that represents the dash offset of the current line material.
  9945. *
  9946. * @tsl
  9947. * @type {Node<float>}
  9948. */
  9949. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  9950. /**
  9951. * TSL object that represents the point size of the current points material.
  9952. *
  9953. * @tsl
  9954. * @type {Node<float>}
  9955. */
  9956. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  9957. /**
  9958. * TSL object that represents the dispersion of the current material.
  9959. *
  9960. * @tsl
  9961. * @type {Node<float>}
  9962. */
  9963. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9964. /**
  9965. * TSL object that represents the light map of the current material.
  9966. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9967. *
  9968. * @tsl
  9969. * @type {Node<vec3>}
  9970. */
  9971. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9972. /**
  9973. * TSL object that represents the ambient occlusion map of the current material.
  9974. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9975. *
  9976. * @tsl
  9977. * @type {Node<float>}
  9978. */
  9979. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9980. /**
  9981. * TSL object that represents the anisotropy vector of the current material.
  9982. *
  9983. * @tsl
  9984. * @type {Node<vec2>}
  9985. */
  9986. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9987. return frame.material;
  9988. } ).onRenderUpdate( function ( { material } ) {
  9989. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9990. } );
  9991. /**
  9992. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9993. *
  9994. * @tsl
  9995. * @type {VaryingNode<vec4>}
  9996. */
  9997. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9998. return builder.context.setupModelViewProjection();
  9999. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10000. /**
  10001. * This class represents shader indices of different types. The following predefined node
  10002. * objects cover frequent use cases:
  10003. *
  10004. * - `vertexIndex`: The index of a vertex within a mesh.
  10005. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10006. * - `drawIndex`: The index of a draw call.
  10007. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10008. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10009. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10010. *
  10011. * @augments Node
  10012. */
  10013. class IndexNode extends Node {
  10014. static get type() {
  10015. return 'IndexNode';
  10016. }
  10017. /**
  10018. * Constructs a new index node.
  10019. *
  10020. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10021. */
  10022. constructor( scope ) {
  10023. super( 'uint' );
  10024. /**
  10025. * The scope of the index node.
  10026. *
  10027. * @type {string}
  10028. */
  10029. this.scope = scope;
  10030. /**
  10031. * This flag can be used for type testing.
  10032. *
  10033. * @type {boolean}
  10034. * @readonly
  10035. * @default true
  10036. */
  10037. this.isIndexNode = true;
  10038. }
  10039. generate( builder ) {
  10040. const nodeType = this.getNodeType( builder );
  10041. const scope = this.scope;
  10042. let propertyName;
  10043. if ( scope === IndexNode.VERTEX ) {
  10044. propertyName = builder.getVertexIndex();
  10045. } else if ( scope === IndexNode.INSTANCE ) {
  10046. propertyName = builder.getInstanceIndex();
  10047. } else if ( scope === IndexNode.DRAW ) {
  10048. propertyName = builder.getDrawIndex();
  10049. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10050. propertyName = builder.getInvocationLocalIndex();
  10051. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10052. propertyName = builder.getInvocationSubgroupIndex();
  10053. } else if ( scope === IndexNode.SUBGROUP ) {
  10054. propertyName = builder.getSubgroupIndex();
  10055. } else {
  10056. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10057. }
  10058. let output;
  10059. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10060. output = propertyName;
  10061. } else {
  10062. const nodeVarying = varying( this );
  10063. output = nodeVarying.build( builder, nodeType );
  10064. }
  10065. return output;
  10066. }
  10067. }
  10068. IndexNode.VERTEX = 'vertex';
  10069. IndexNode.INSTANCE = 'instance';
  10070. IndexNode.SUBGROUP = 'subgroup';
  10071. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10072. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10073. IndexNode.DRAW = 'draw';
  10074. /**
  10075. * TSL object that represents the index of a vertex within a mesh.
  10076. *
  10077. * @tsl
  10078. * @type {IndexNode}
  10079. */
  10080. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10081. /**
  10082. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10083. *
  10084. * @tsl
  10085. * @type {IndexNode}
  10086. */
  10087. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10088. /**
  10089. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10090. *
  10091. * @tsl
  10092. * @type {IndexNode}
  10093. */
  10094. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  10095. /**
  10096. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  10097. *
  10098. * @tsl
  10099. * @type {IndexNode}
  10100. */
  10101. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  10102. /**
  10103. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  10104. *
  10105. * @tsl
  10106. * @type {IndexNode}
  10107. */
  10108. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  10109. /**
  10110. * TSL object that represents the index of a draw call.
  10111. *
  10112. * @tsl
  10113. * @type {IndexNode}
  10114. */
  10115. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  10116. /**
  10117. * This node implements the vertex shader logic which is required
  10118. * when rendering 3D objects via instancing. The code makes sure
  10119. * vertex positions, normals and colors can be modified via instanced
  10120. * data.
  10121. *
  10122. * @augments Node
  10123. */
  10124. class InstanceNode extends Node {
  10125. static get type() {
  10126. return 'InstanceNode';
  10127. }
  10128. /**
  10129. * Constructs a new instance node.
  10130. *
  10131. * @param {number} count - The number of instances.
  10132. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10133. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10134. */
  10135. constructor( count, instanceMatrix, instanceColor = null ) {
  10136. super( 'void' );
  10137. /**
  10138. * The number of instances.
  10139. *
  10140. * @type {number}
  10141. */
  10142. this.count = count;
  10143. /**
  10144. * Instanced buffer attribute representing the transformation of instances.
  10145. *
  10146. * @type {InstancedBufferAttribute}
  10147. */
  10148. this.instanceMatrix = instanceMatrix;
  10149. /**
  10150. * Instanced buffer attribute representing the color of instances.
  10151. *
  10152. * @type {InstancedBufferAttribute}
  10153. */
  10154. this.instanceColor = instanceColor;
  10155. /**
  10156. * The node that represents the instance matrix data.
  10157. *
  10158. * @type {?Node}
  10159. */
  10160. this.instanceMatrixNode = null;
  10161. /**
  10162. * The node that represents the instance color data.
  10163. *
  10164. * @type {?Node}
  10165. * @default null
  10166. */
  10167. this.instanceColorNode = null;
  10168. /**
  10169. * The update type is set to `frame` since an update
  10170. * of instanced buffer data must be checked per frame.
  10171. *
  10172. * @type {string}
  10173. * @default 'frame'
  10174. */
  10175. this.updateType = NodeUpdateType.FRAME;
  10176. /**
  10177. * A reference to a buffer that is used by `instanceMatrixNode`.
  10178. *
  10179. * @type {?InstancedInterleavedBuffer}
  10180. */
  10181. this.buffer = null;
  10182. /**
  10183. * A reference to a buffer that is used by `instanceColorNode`.
  10184. *
  10185. * @type {?InstancedBufferAttribute}
  10186. */
  10187. this.bufferColor = null;
  10188. }
  10189. /**
  10190. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10191. * to predefined node variables for accumulation. That follows the same patterns
  10192. * like with morph and skinning nodes.
  10193. *
  10194. * @param {NodeBuilder} builder - The current node builder.
  10195. */
  10196. setup( builder ) {
  10197. const { count, instanceMatrix, instanceColor } = this;
  10198. let { instanceMatrixNode, instanceColorNode } = this;
  10199. if ( instanceMatrixNode === null ) {
  10200. // 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.
  10201. if ( count <= 1000 ) {
  10202. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  10203. } else {
  10204. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  10205. this.buffer = buffer;
  10206. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10207. const instanceBuffers = [
  10208. // F.Signature -> bufferAttribute( array, type, stride, offset )
  10209. bufferFn( buffer, 'vec4', 16, 0 ),
  10210. bufferFn( buffer, 'vec4', 16, 4 ),
  10211. bufferFn( buffer, 'vec4', 16, 8 ),
  10212. bufferFn( buffer, 'vec4', 16, 12 )
  10213. ];
  10214. instanceMatrixNode = mat4( ...instanceBuffers );
  10215. }
  10216. this.instanceMatrixNode = instanceMatrixNode;
  10217. }
  10218. if ( instanceColor && instanceColorNode === null ) {
  10219. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  10220. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10221. this.bufferColor = buffer;
  10222. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  10223. this.instanceColorNode = instanceColorNode;
  10224. }
  10225. // POSITION
  10226. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  10227. positionLocal.assign( instancePosition );
  10228. // NORMAL
  10229. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10230. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  10231. // ASSIGNS
  10232. normalLocal.assign( instanceNormal );
  10233. }
  10234. // COLOR
  10235. if ( this.instanceColorNode !== null ) {
  10236. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  10237. }
  10238. }
  10239. /**
  10240. * Checks if the internal buffers required an update.
  10241. *
  10242. * @param {NodeFrame} frame - The current node frame.
  10243. */
  10244. update( /*frame*/ ) {
  10245. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  10246. this.buffer.version = this.instanceMatrix.version;
  10247. }
  10248. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  10249. this.bufferColor.version = this.instanceColor.version;
  10250. }
  10251. }
  10252. }
  10253. /**
  10254. * TSL function for creating an instance node.
  10255. *
  10256. * @tsl
  10257. * @function
  10258. * @param {number} count - The number of instances.
  10259. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10260. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10261. * @returns {InstanceNode}
  10262. */
  10263. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  10264. /**
  10265. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  10266. * It allows an easier setup of the instance node.
  10267. *
  10268. * @augments InstanceNode
  10269. */
  10270. class InstancedMeshNode extends InstanceNode {
  10271. static get type() {
  10272. return 'InstancedMeshNode';
  10273. }
  10274. /**
  10275. * Constructs a new instanced mesh node.
  10276. *
  10277. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  10278. */
  10279. constructor( instancedMesh ) {
  10280. const { count, instanceMatrix, instanceColor } = instancedMesh;
  10281. super( count, instanceMatrix, instanceColor );
  10282. /**
  10283. * A reference to the instanced mesh.
  10284. *
  10285. * @type {InstancedMesh}
  10286. */
  10287. this.instancedMesh = instancedMesh;
  10288. }
  10289. }
  10290. /**
  10291. * TSL function for creating an instanced mesh node.
  10292. *
  10293. * @tsl
  10294. * @function
  10295. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  10296. * @returns {InstancedMeshNode}
  10297. */
  10298. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  10299. /**
  10300. * This node implements the vertex shader logic which is required
  10301. * when rendering 3D objects via batching. `BatchNode` must be used
  10302. * with instances of {@link BatchedMesh}.
  10303. *
  10304. * @augments Node
  10305. */
  10306. class BatchNode extends Node {
  10307. static get type() {
  10308. return 'BatchNode';
  10309. }
  10310. /**
  10311. * Constructs a new batch node.
  10312. *
  10313. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10314. */
  10315. constructor( batchMesh ) {
  10316. super( 'void' );
  10317. /**
  10318. * A reference to batched mesh.
  10319. *
  10320. * @type {BatchedMesh}
  10321. */
  10322. this.batchMesh = batchMesh;
  10323. /**
  10324. * The batching index node.
  10325. *
  10326. * @type {?IndexNode}
  10327. * @default null
  10328. */
  10329. this.batchingIdNode = null;
  10330. }
  10331. /**
  10332. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10333. * to predefined node variables for accumulation. That follows the same patterns
  10334. * like with morph and skinning nodes.
  10335. *
  10336. * @param {NodeBuilder} builder - The current node builder.
  10337. */
  10338. setup( builder ) {
  10339. if ( this.batchingIdNode === null ) {
  10340. if ( builder.getDrawIndex() === null ) {
  10341. this.batchingIdNode = instanceIndex;
  10342. } else {
  10343. this.batchingIdNode = drawIndex;
  10344. }
  10345. }
  10346. const getIndirectIndex = Fn( ( [ id ] ) => {
  10347. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  10348. const x = int( id ).mod( size );
  10349. const y = int( id ).div( size );
  10350. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  10351. } ).setLayout( {
  10352. name: 'getIndirectIndex',
  10353. type: 'uint',
  10354. inputs: [
  10355. { name: 'id', type: 'int' }
  10356. ]
  10357. } );
  10358. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  10359. const matricesTexture = this.batchMesh._matricesTexture;
  10360. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  10361. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  10362. const x = j.mod( size );
  10363. const y = j.div( size );
  10364. const batchingMatrix = mat4(
  10365. textureLoad( matricesTexture, ivec2( x, y ) ),
  10366. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  10367. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  10368. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  10369. );
  10370. const colorsTexture = this.batchMesh._colorsTexture;
  10371. if ( colorsTexture !== null ) {
  10372. const getBatchingColor = Fn( ( [ id ] ) => {
  10373. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  10374. const j = id;
  10375. const x = j.mod( size );
  10376. const y = j.div( size );
  10377. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  10378. } ).setLayout( {
  10379. name: 'getBatchingColor',
  10380. type: 'vec3',
  10381. inputs: [
  10382. { name: 'id', type: 'int' }
  10383. ]
  10384. } );
  10385. const color = getBatchingColor( indirectId );
  10386. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  10387. }
  10388. const bm = mat3( batchingMatrix );
  10389. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  10390. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  10391. const batchingNormal = bm.mul( transformedNormal ).xyz;
  10392. normalLocal.assign( batchingNormal );
  10393. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10394. tangentLocal.mulAssign( bm );
  10395. }
  10396. }
  10397. }
  10398. /**
  10399. * TSL function for creating a batch node.
  10400. *
  10401. * @tsl
  10402. * @function
  10403. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10404. * @returns {BatchNode}
  10405. */
  10406. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  10407. /**
  10408. * This class enables element access on instances of {@link StorageBufferNode}.
  10409. * In most cases, it is indirectly used when accessing elements with the
  10410. * {@link StorageBufferNode#element} method.
  10411. *
  10412. * ```js
  10413. * const position = positionStorage.element( instanceIndex );
  10414. * ```
  10415. *
  10416. * @augments ArrayElementNode
  10417. */
  10418. class StorageArrayElementNode extends ArrayElementNode {
  10419. static get type() {
  10420. return 'StorageArrayElementNode';
  10421. }
  10422. /**
  10423. * Constructs storage buffer element node.
  10424. *
  10425. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10426. * @param {Node} indexNode - The index node that defines the element access.
  10427. */
  10428. constructor( storageBufferNode, indexNode ) {
  10429. super( storageBufferNode, indexNode );
  10430. /**
  10431. * This flag can be used for type testing.
  10432. *
  10433. * @type {boolean}
  10434. * @readonly
  10435. * @default true
  10436. */
  10437. this.isStorageArrayElementNode = true;
  10438. }
  10439. /**
  10440. * The storage buffer node.
  10441. *
  10442. * @param {Node} value
  10443. * @type {StorageBufferNode}
  10444. */
  10445. set storageBufferNode( value ) {
  10446. this.node = value;
  10447. }
  10448. get storageBufferNode() {
  10449. return this.node;
  10450. }
  10451. getMemberType( builder, name ) {
  10452. const structTypeNode = this.storageBufferNode.structTypeNode;
  10453. if ( structTypeNode ) {
  10454. return structTypeNode.getMemberType( builder, name );
  10455. }
  10456. return 'void';
  10457. }
  10458. setup( builder ) {
  10459. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10460. if ( this.node.isPBO === true ) {
  10461. builder.setupPBO( this.node );
  10462. }
  10463. }
  10464. return super.setup( builder );
  10465. }
  10466. generate( builder, output ) {
  10467. let snippet;
  10468. const isAssignContext = builder.context.assign;
  10469. //
  10470. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10471. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  10472. snippet = builder.generatePBO( this );
  10473. } else {
  10474. snippet = this.node.build( builder );
  10475. }
  10476. } else {
  10477. snippet = super.generate( builder );
  10478. }
  10479. if ( isAssignContext !== true ) {
  10480. const type = this.getNodeType( builder );
  10481. snippet = builder.format( snippet, type, output );
  10482. }
  10483. return snippet;
  10484. }
  10485. }
  10486. /**
  10487. * TSL function for creating a storage element node.
  10488. *
  10489. * @tsl
  10490. * @function
  10491. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10492. * @param {Node} indexNode - The index node that defines the element access.
  10493. * @returns {StorageArrayElementNode}
  10494. */
  10495. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  10496. /**
  10497. * This node is used in context of compute shaders and allows to define a
  10498. * storage buffer for data. A typical workflow is to create instances of
  10499. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  10500. * setup up a compute shader that writes into the buffers and then convert
  10501. * the storage buffers to attribute nodes for rendering.
  10502. *
  10503. * ```js
  10504. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  10505. *
  10506. * const computeInit = Fn( () => { // the compute shader
  10507. *
  10508. * const position = positionBuffer.element( instanceIndex );
  10509. *
  10510. * // compute position data
  10511. *
  10512. * position.x = 1;
  10513. * position.y = 1;
  10514. * position.z = 1;
  10515. *
  10516. * } )().compute( particleCount );
  10517. *
  10518. * const particleMaterial = new THREE.SpriteNodeMaterial();
  10519. * particleMaterial.positionNode = positionBuffer.toAttribute();
  10520. *
  10521. * renderer.computeAsync( computeInit );
  10522. *
  10523. * ```
  10524. *
  10525. * @augments BufferNode
  10526. */
  10527. class StorageBufferNode extends BufferNode {
  10528. static get type() {
  10529. return 'StorageBufferNode';
  10530. }
  10531. /**
  10532. * Constructs a new storage buffer node.
  10533. *
  10534. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10535. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  10536. * @param {number} [bufferCount=0] - The buffer count.
  10537. */
  10538. constructor( value, bufferType = null, bufferCount = 0 ) {
  10539. let nodeType, structTypeNode = null;
  10540. if ( bufferType && bufferType.isStruct ) {
  10541. nodeType = 'struct';
  10542. structTypeNode = bufferType.layout;
  10543. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  10544. bufferCount = value.count;
  10545. }
  10546. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  10547. nodeType = getTypeFromLength( value.itemSize );
  10548. bufferCount = value.count;
  10549. } else {
  10550. nodeType = bufferType;
  10551. }
  10552. super( value, nodeType, bufferCount );
  10553. /**
  10554. * This flag can be used for type testing.
  10555. *
  10556. * @type {boolean}
  10557. * @readonly
  10558. * @default true
  10559. */
  10560. this.isStorageBufferNode = true;
  10561. /**
  10562. * The buffer struct type.
  10563. *
  10564. * @type {?StructTypeNode}
  10565. * @default null
  10566. */
  10567. this.structTypeNode = structTypeNode;
  10568. /**
  10569. * The access type of the texture node.
  10570. *
  10571. * @type {string}
  10572. * @default 'readWrite'
  10573. */
  10574. this.access = NodeAccess.READ_WRITE;
  10575. /**
  10576. * Whether the node is atomic or not.
  10577. *
  10578. * @type {boolean}
  10579. * @default false
  10580. */
  10581. this.isAtomic = false;
  10582. /**
  10583. * Whether the node represents a PBO or not.
  10584. * Only relevant for WebGL.
  10585. *
  10586. * @type {boolean}
  10587. * @default false
  10588. */
  10589. this.isPBO = false;
  10590. /**
  10591. * A reference to the internal buffer attribute node.
  10592. *
  10593. * @type {?BufferAttributeNode}
  10594. * @default null
  10595. */
  10596. this._attribute = null;
  10597. /**
  10598. * A reference to the internal varying node.
  10599. *
  10600. * @type {?VaryingNode}
  10601. * @default null
  10602. */
  10603. this._varying = null;
  10604. /**
  10605. * `StorageBufferNode` sets this property to `true` by default.
  10606. *
  10607. * @type {boolean}
  10608. * @default true
  10609. */
  10610. this.global = true;
  10611. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10612. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10613. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10614. else value.isStorageBufferAttribute = true;
  10615. }
  10616. }
  10617. /**
  10618. * This method is overwritten since the buffer data might be shared
  10619. * and thus the hash should be shared as well.
  10620. *
  10621. * @param {NodeBuilder} builder - The current node builder.
  10622. * @return {string} The hash.
  10623. */
  10624. getHash( builder ) {
  10625. if ( this.bufferCount === 0 ) {
  10626. let bufferData = builder.globalCache.getData( this.value );
  10627. if ( bufferData === undefined ) {
  10628. bufferData = {
  10629. node: this
  10630. };
  10631. builder.globalCache.setData( this.value, bufferData );
  10632. }
  10633. return bufferData.node.uuid;
  10634. }
  10635. return this.uuid;
  10636. }
  10637. /**
  10638. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  10639. *
  10640. * @param {NodeBuilder} builder - The current node builder.
  10641. * @return {string} The input type.
  10642. */
  10643. getInputType( /*builder*/ ) {
  10644. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10645. }
  10646. /**
  10647. * Enables element access with the given index node.
  10648. *
  10649. * @param {IndexNode} indexNode - The index node.
  10650. * @return {StorageArrayElementNode} A node representing the element access.
  10651. */
  10652. element( indexNode ) {
  10653. return storageElement( this, indexNode );
  10654. }
  10655. /**
  10656. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  10657. *
  10658. * @param {boolean} value - The value so set.
  10659. * @return {StorageBufferNode} A reference to this node.
  10660. */
  10661. setPBO( value ) {
  10662. this.isPBO = value;
  10663. return this;
  10664. }
  10665. /**
  10666. * Returns the `isPBO` value.
  10667. *
  10668. * @return {boolean} Whether the node represents a PBO or not.
  10669. */
  10670. getPBO() {
  10671. return this.isPBO;
  10672. }
  10673. /**
  10674. * Defines the node access.
  10675. *
  10676. * @param {string} value - The node access.
  10677. * @return {StorageBufferNode} A reference to this node.
  10678. */
  10679. setAccess( value ) {
  10680. this.access = value;
  10681. return this;
  10682. }
  10683. /**
  10684. * Convenience method for configuring a read-only node access.
  10685. *
  10686. * @return {StorageBufferNode} A reference to this node.
  10687. */
  10688. toReadOnly() {
  10689. return this.setAccess( NodeAccess.READ_ONLY );
  10690. }
  10691. /**
  10692. * Defines whether the node is atomic or not.
  10693. *
  10694. * @param {boolean} value - The atomic flag.
  10695. * @return {StorageBufferNode} A reference to this node.
  10696. */
  10697. setAtomic( value ) {
  10698. this.isAtomic = value;
  10699. return this;
  10700. }
  10701. /**
  10702. * Convenience method for making this node atomic.
  10703. *
  10704. * @return {StorageBufferNode} A reference to this node.
  10705. */
  10706. toAtomic() {
  10707. return this.setAtomic( true );
  10708. }
  10709. /**
  10710. * Returns attribute data for this storage buffer node.
  10711. *
  10712. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  10713. */
  10714. getAttributeData() {
  10715. if ( this._attribute === null ) {
  10716. this._attribute = bufferAttribute( this.value );
  10717. this._varying = varying( this._attribute );
  10718. }
  10719. return {
  10720. attribute: this._attribute,
  10721. varying: this._varying
  10722. };
  10723. }
  10724. /**
  10725. * This method is overwritten since the node type from the availability of storage buffers
  10726. * and the attribute data.
  10727. *
  10728. * @param {NodeBuilder} builder - The current node builder.
  10729. * @return {string} The node type.
  10730. */
  10731. getNodeType( builder ) {
  10732. if ( this.structTypeNode !== null ) {
  10733. return this.structTypeNode.getNodeType( builder );
  10734. }
  10735. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10736. return super.getNodeType( builder );
  10737. }
  10738. const { attribute } = this.getAttributeData();
  10739. return attribute.getNodeType( builder );
  10740. }
  10741. /**
  10742. * Generates the code snippet of the storage buffer node.
  10743. *
  10744. * @param {NodeBuilder} builder - The current node builder.
  10745. * @return {string} The generated code snippet.
  10746. */
  10747. generate( builder ) {
  10748. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  10749. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10750. return super.generate( builder );
  10751. }
  10752. const { attribute, varying } = this.getAttributeData();
  10753. const output = varying.build( builder );
  10754. builder.registerTransform( output, attribute );
  10755. return output;
  10756. }
  10757. }
  10758. /**
  10759. * TSL function for creating a storage buffer node.
  10760. *
  10761. * @tsl
  10762. * @function
  10763. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10764. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  10765. * @param {number} [count=0] - The buffer count.
  10766. * @returns {StorageBufferNode}
  10767. */
  10768. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10769. /**
  10770. * @tsl
  10771. * @function
  10772. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  10773. *
  10774. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10775. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  10776. * @param {number} count - The buffer count.
  10777. * @returns {StorageBufferNode}
  10778. */
  10779. const storageObject = ( value, type, count ) => { // @deprecated, r171
  10780. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  10781. return storage( value, type, count ).setPBO( true );
  10782. };
  10783. const _frameId = new WeakMap();
  10784. /**
  10785. * This node implements the vertex transformation shader logic which is required
  10786. * for skinning/skeletal animation.
  10787. *
  10788. * @augments Node
  10789. */
  10790. class SkinningNode extends Node {
  10791. static get type() {
  10792. return 'SkinningNode';
  10793. }
  10794. /**
  10795. * Constructs a new skinning node.
  10796. *
  10797. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10798. */
  10799. constructor( skinnedMesh ) {
  10800. super( 'void' );
  10801. /**
  10802. * The skinned mesh.
  10803. *
  10804. * @type {SkinnedMesh}
  10805. */
  10806. this.skinnedMesh = skinnedMesh;
  10807. /**
  10808. * The update type overwritten since skinning nodes are updated per object.
  10809. *
  10810. * @type {string}
  10811. */
  10812. this.updateType = NodeUpdateType.OBJECT;
  10813. //
  10814. /**
  10815. * The skin index attribute.
  10816. *
  10817. * @type {AttributeNode}
  10818. */
  10819. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  10820. /**
  10821. * The skin weight attribute.
  10822. *
  10823. * @type {AttributeNode}
  10824. */
  10825. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  10826. /**
  10827. * The bind matrix node.
  10828. *
  10829. * @type {Node<mat4>}
  10830. */
  10831. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  10832. /**
  10833. * The bind matrix inverse node.
  10834. *
  10835. * @type {Node<mat4>}
  10836. */
  10837. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  10838. /**
  10839. * The bind matrices as a uniform buffer node.
  10840. *
  10841. * @type {Node}
  10842. */
  10843. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10844. /**
  10845. * The current vertex position in local space.
  10846. *
  10847. * @type {Node<vec3>}
  10848. */
  10849. this.positionNode = positionLocal;
  10850. /**
  10851. * The result of vertex position in local space.
  10852. *
  10853. * @type {Node<vec3>}
  10854. */
  10855. this.toPositionNode = positionLocal;
  10856. /**
  10857. * The previous bind matrices as a uniform buffer node.
  10858. * Required for computing motion vectors.
  10859. *
  10860. * @type {?Node}
  10861. * @default null
  10862. */
  10863. this.previousBoneMatricesNode = null;
  10864. }
  10865. /**
  10866. * Transforms the given vertex position via skinning.
  10867. *
  10868. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10869. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  10870. * @return {Node<vec3>} The transformed vertex position.
  10871. */
  10872. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  10873. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10874. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10875. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10876. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10877. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10878. // POSITION
  10879. const skinVertex = bindMatrixNode.mul( position );
  10880. const skinned = add(
  10881. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  10882. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  10883. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  10884. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  10885. );
  10886. return bindMatrixInverseNode.mul( skinned ).xyz;
  10887. }
  10888. /**
  10889. * Transforms the given vertex normal via skinning.
  10890. *
  10891. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  10892. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  10893. * @return {Node<vec3>} The transformed vertex normal.
  10894. */
  10895. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  10896. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  10897. const boneMatX = boneMatrices.element( skinIndexNode.x );
  10898. const boneMatY = boneMatrices.element( skinIndexNode.y );
  10899. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  10900. const boneMatW = boneMatrices.element( skinIndexNode.w );
  10901. // NORMAL
  10902. let skinMatrix = add(
  10903. skinWeightNode.x.mul( boneMatX ),
  10904. skinWeightNode.y.mul( boneMatY ),
  10905. skinWeightNode.z.mul( boneMatZ ),
  10906. skinWeightNode.w.mul( boneMatW )
  10907. );
  10908. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  10909. return skinMatrix.transformDirection( normal ).xyz;
  10910. }
  10911. /**
  10912. * Computes the transformed/skinned vertex position of the previous frame.
  10913. *
  10914. * @param {NodeBuilder} builder - The current node builder.
  10915. * @return {Node<vec3>} The skinned position from the previous frame.
  10916. */
  10917. getPreviousSkinnedPosition( builder ) {
  10918. const skinnedMesh = builder.object;
  10919. if ( this.previousBoneMatricesNode === null ) {
  10920. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  10921. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  10922. }
  10923. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  10924. }
  10925. /**
  10926. * Returns `true` if bone matrices from the previous frame are required. Relevant
  10927. * when computing motion vectors with {@link VelocityNode}.
  10928. *
  10929. * @param {NodeBuilder} builder - The current node builder.
  10930. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  10931. */
  10932. needsPreviousBoneMatrices( builder ) {
  10933. const mrt = builder.renderer.getMRT();
  10934. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  10935. }
  10936. /**
  10937. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  10938. *
  10939. * @param {NodeBuilder} builder - The current node builder.
  10940. * @return {Node<vec3>} The transformed vertex position.
  10941. */
  10942. setup( builder ) {
  10943. if ( this.needsPreviousBoneMatrices( builder ) ) {
  10944. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  10945. }
  10946. const skinPosition = this.getSkinnedPosition();
  10947. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  10948. //
  10949. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10950. const skinNormal = this.getSkinnedNormal();
  10951. normalLocal.assign( skinNormal );
  10952. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10953. tangentLocal.assign( skinNormal );
  10954. }
  10955. }
  10956. return skinPosition;
  10957. }
  10958. /**
  10959. * Generates the code snippet of the skinning node.
  10960. *
  10961. * @param {NodeBuilder} builder - The current node builder.
  10962. * @param {string} output - The current output.
  10963. * @return {string} The generated code snippet.
  10964. */
  10965. generate( builder, output ) {
  10966. if ( output !== 'void' ) {
  10967. return super.generate( builder, output );
  10968. }
  10969. }
  10970. /**
  10971. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  10972. *
  10973. * @param {NodeFrame} frame - The current node frame.
  10974. */
  10975. update( frame ) {
  10976. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  10977. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  10978. _frameId.set( skeleton, frame.frameId );
  10979. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  10980. skeleton.update();
  10981. }
  10982. }
  10983. /**
  10984. * TSL function for creating a skinning node.
  10985. *
  10986. * @tsl
  10987. * @function
  10988. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10989. * @returns {SkinningNode}
  10990. */
  10991. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  10992. /**
  10993. * TSL function for computing skinning.
  10994. *
  10995. * @tsl
  10996. * @function
  10997. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10998. * @param {Node<vec3>} [toPosition=null] - The target position.
  10999. * @returns {SkinningNode}
  11000. */
  11001. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11002. const node = new SkinningNode( skinnedMesh );
  11003. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11004. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11005. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11006. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11007. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11008. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11009. node.toPositionNode = toPosition;
  11010. return nodeObject( node );
  11011. };
  11012. /**
  11013. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11014. * ```js
  11015. * Loop( count, ( { i } ) => {
  11016. *
  11017. * } );
  11018. * ```
  11019. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11020. * ```js
  11021. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11022. *
  11023. * } );
  11024. *```
  11025. * Nested loops can be defined in a compacted form:
  11026. * ```js
  11027. * Loop( 10, 5, ( { i, j } ) => {
  11028. *
  11029. * } );
  11030. * ```
  11031. * Loops that should run backwards can be defined like so:
  11032. * ```js
  11033. * Loop( { start: 10 }, () => {} );
  11034. * ```
  11035. * It is possible to execute with boolean values, similar to the `while` syntax.
  11036. * ```js
  11037. * const value = float( 0 ).toVar();
  11038. *
  11039. * Loop( value.lessThan( 10 ), () => {
  11040. *
  11041. * value.addAssign( 1 );
  11042. *
  11043. * } );
  11044. * ```
  11045. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11046. * @augments Node
  11047. */
  11048. class LoopNode extends Node {
  11049. static get type() {
  11050. return 'LoopNode';
  11051. }
  11052. /**
  11053. * Constructs a new loop node.
  11054. *
  11055. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11056. */
  11057. constructor( params = [] ) {
  11058. super();
  11059. this.params = params;
  11060. }
  11061. /**
  11062. * Returns a loop variable name based on an index. The pattern is
  11063. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11064. *
  11065. * @param {number} index - The index.
  11066. * @return {string} The loop variable name.
  11067. */
  11068. getVarName( index ) {
  11069. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11070. }
  11071. /**
  11072. * Returns properties about this node.
  11073. *
  11074. * @param {NodeBuilder} builder - The current node builder.
  11075. * @return {Object} The node properties.
  11076. */
  11077. getProperties( builder ) {
  11078. const properties = builder.getNodeProperties( this );
  11079. if ( properties.stackNode !== undefined ) return properties;
  11080. //
  11081. const inputs = {};
  11082. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11083. const param = this.params[ i ];
  11084. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  11085. const type = ( param.isNode !== true && param.type ) || 'int';
  11086. inputs[ name ] = expression( name, type );
  11087. }
  11088. const stack = builder.addStack(); // TODO: cache() it
  11089. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  11090. properties.stackNode = stack;
  11091. const baseParam = this.params[ 0 ];
  11092. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  11093. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  11094. }
  11095. builder.removeStack();
  11096. return properties;
  11097. }
  11098. /**
  11099. * This method is overwritten since the node type is inferred based on the loop configuration.
  11100. *
  11101. * @param {NodeBuilder} builder - The current node builder.
  11102. * @return {string} The node type.
  11103. */
  11104. getNodeType( builder ) {
  11105. const { returnsNode } = this.getProperties( builder );
  11106. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  11107. }
  11108. setup( builder ) {
  11109. // setup properties
  11110. this.getProperties( builder );
  11111. }
  11112. generate( builder ) {
  11113. const properties = this.getProperties( builder );
  11114. const params = this.params;
  11115. const stackNode = properties.stackNode;
  11116. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  11117. const param = params[ i ];
  11118. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  11119. if ( param.isNode ) {
  11120. if ( param.getNodeType( builder ) === 'bool' ) {
  11121. isWhile = true;
  11122. type = 'bool';
  11123. end = param.build( builder, type );
  11124. } else {
  11125. type = 'int';
  11126. name = this.getVarName( i );
  11127. start = '0';
  11128. end = param.build( builder, type );
  11129. condition = '<';
  11130. }
  11131. } else {
  11132. type = param.type || 'int';
  11133. name = param.name || this.getVarName( i );
  11134. start = param.start;
  11135. end = param.end;
  11136. condition = param.condition;
  11137. update = param.update;
  11138. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  11139. else if ( start && start.isNode ) start = start.build( builder, type );
  11140. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  11141. else if ( end && end.isNode ) end = end.build( builder, type );
  11142. if ( start !== undefined && end === undefined ) {
  11143. start = start + ' - 1';
  11144. end = '0';
  11145. condition = '>=';
  11146. } else if ( end !== undefined && start === undefined ) {
  11147. start = '0';
  11148. condition = '<';
  11149. }
  11150. if ( condition === undefined ) {
  11151. if ( Number( start ) > Number( end ) ) {
  11152. condition = '>=';
  11153. } else {
  11154. condition = '<';
  11155. }
  11156. }
  11157. }
  11158. let loopSnippet;
  11159. if ( isWhile ) {
  11160. loopSnippet = `while ( ${ end } )`;
  11161. } else {
  11162. const internalParam = { start, end};
  11163. //
  11164. const startSnippet = internalParam.start;
  11165. const endSnippet = internalParam.end;
  11166. let updateSnippet;
  11167. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  11168. if ( update !== undefined && update !== null ) {
  11169. switch ( typeof update ) {
  11170. case 'function':
  11171. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  11172. const snippet = flow.code.replace( /\t|;/g, '' );
  11173. updateSnippet = snippet;
  11174. break;
  11175. case 'number':
  11176. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  11177. break;
  11178. case 'string':
  11179. updateSnippet = name + ' ' + update;
  11180. break;
  11181. default:
  11182. if ( update.isNode ) {
  11183. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  11184. } else {
  11185. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  11186. updateSnippet = 'break /* invalid update */';
  11187. }
  11188. }
  11189. } else {
  11190. if ( type === 'int' || type === 'uint' ) {
  11191. update = condition.includes( '<' ) ? '++' : '--';
  11192. } else {
  11193. update = deltaOperator() + ' 1.';
  11194. }
  11195. updateSnippet = name + ' ' + update;
  11196. }
  11197. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  11198. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  11199. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  11200. }
  11201. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  11202. }
  11203. const stackSnippet = stackNode.build( builder, 'void' );
  11204. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  11205. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  11206. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11207. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  11208. }
  11209. builder.addFlowTab();
  11210. return returnsSnippet;
  11211. }
  11212. }
  11213. /**
  11214. * TSL function for creating a loop node.
  11215. *
  11216. * @tsl
  11217. * @function
  11218. * @param {...any} params - A list of parameters.
  11219. * @returns {LoopNode}
  11220. */
  11221. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  11222. /**
  11223. * TSL function for creating a `Continue()` expression.
  11224. *
  11225. * @tsl
  11226. * @function
  11227. * @returns {ExpressionNode}
  11228. */
  11229. const Continue = () => expression( 'continue' ).toStack();
  11230. /**
  11231. * TSL function for creating a `Break()` expression.
  11232. *
  11233. * @tsl
  11234. * @function
  11235. * @returns {ExpressionNode}
  11236. */
  11237. const Break = () => expression( 'break' ).toStack();
  11238. // Deprecated
  11239. /**
  11240. * @tsl
  11241. * @function
  11242. * @deprecated since r168. Use {@link Loop} instead.
  11243. *
  11244. * @param {...any} params
  11245. * @returns {LoopNode}
  11246. */
  11247. const loop = ( ...params ) => { // @deprecated, r168
  11248. console.warn( 'THREE.TSL: loop() has been renamed to Loop().' );
  11249. return Loop( ...params );
  11250. };
  11251. const _morphTextures = /*@__PURE__*/ new WeakMap();
  11252. const _morphVec4 = /*@__PURE__*/ new Vector4();
  11253. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  11254. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  11255. const y = texelIndex.div( width );
  11256. const x = texelIndex.sub( y.mul( width ) );
  11257. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  11258. return bufferAttrib.mul( influence );
  11259. } );
  11260. function getEntry( geometry ) {
  11261. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11262. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  11263. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  11264. // instead of using attributes, the WebGL 2 code path encodes morph targets
  11265. // into an array of data textures. Each layer represents a single morph target.
  11266. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11267. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11268. let entry = _morphTextures.get( geometry );
  11269. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  11270. if ( entry !== undefined ) entry.texture.dispose();
  11271. const morphTargets = geometry.morphAttributes.position || [];
  11272. const morphNormals = geometry.morphAttributes.normal || [];
  11273. const morphColors = geometry.morphAttributes.color || [];
  11274. let vertexDataCount = 0;
  11275. if ( hasMorphPosition === true ) vertexDataCount = 1;
  11276. if ( hasMorphNormals === true ) vertexDataCount = 2;
  11277. if ( hasMorphColors === true ) vertexDataCount = 3;
  11278. let width = geometry.attributes.position.count * vertexDataCount;
  11279. let height = 1;
  11280. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  11281. if ( width > maxTextureSize ) {
  11282. height = Math.ceil( width / maxTextureSize );
  11283. width = maxTextureSize;
  11284. }
  11285. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  11286. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  11287. bufferTexture.type = FloatType;
  11288. bufferTexture.needsUpdate = true;
  11289. // fill buffer
  11290. const vertexDataStride = vertexDataCount * 4;
  11291. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  11292. const morphTarget = morphTargets[ i ];
  11293. const morphNormal = morphNormals[ i ];
  11294. const morphColor = morphColors[ i ];
  11295. const offset = width * height * 4 * i;
  11296. for ( let j = 0; j < morphTarget.count; j ++ ) {
  11297. const stride = j * vertexDataStride;
  11298. if ( hasMorphPosition === true ) {
  11299. _morphVec4.fromBufferAttribute( morphTarget, j );
  11300. buffer[ offset + stride + 0 ] = _morphVec4.x;
  11301. buffer[ offset + stride + 1 ] = _morphVec4.y;
  11302. buffer[ offset + stride + 2 ] = _morphVec4.z;
  11303. buffer[ offset + stride + 3 ] = 0;
  11304. }
  11305. if ( hasMorphNormals === true ) {
  11306. _morphVec4.fromBufferAttribute( morphNormal, j );
  11307. buffer[ offset + stride + 4 ] = _morphVec4.x;
  11308. buffer[ offset + stride + 5 ] = _morphVec4.y;
  11309. buffer[ offset + stride + 6 ] = _morphVec4.z;
  11310. buffer[ offset + stride + 7 ] = 0;
  11311. }
  11312. if ( hasMorphColors === true ) {
  11313. _morphVec4.fromBufferAttribute( morphColor, j );
  11314. buffer[ offset + stride + 8 ] = _morphVec4.x;
  11315. buffer[ offset + stride + 9 ] = _morphVec4.y;
  11316. buffer[ offset + stride + 10 ] = _morphVec4.z;
  11317. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  11318. }
  11319. }
  11320. }
  11321. entry = {
  11322. count: morphTargetsCount,
  11323. texture: bufferTexture,
  11324. stride: vertexDataCount,
  11325. size: new Vector2( width, height )
  11326. };
  11327. _morphTextures.set( geometry, entry );
  11328. function disposeTexture() {
  11329. bufferTexture.dispose();
  11330. _morphTextures.delete( geometry );
  11331. geometry.removeEventListener( 'dispose', disposeTexture );
  11332. }
  11333. geometry.addEventListener( 'dispose', disposeTexture );
  11334. }
  11335. return entry;
  11336. }
  11337. /**
  11338. * This node implements the vertex transformation shader logic which is required
  11339. * for morph target animation.
  11340. *
  11341. * @augments Node
  11342. */
  11343. class MorphNode extends Node {
  11344. static get type() {
  11345. return 'MorphNode';
  11346. }
  11347. /**
  11348. * Constructs a new morph node.
  11349. *
  11350. * @param {Mesh} mesh - The mesh holding the morph targets.
  11351. */
  11352. constructor( mesh ) {
  11353. super( 'void' );
  11354. /**
  11355. * The mesh holding the morph targets.
  11356. *
  11357. * @type {Mesh}
  11358. */
  11359. this.mesh = mesh;
  11360. /**
  11361. * A uniform node which represents the morph base influence value.
  11362. *
  11363. * @type {UniformNode<float>}
  11364. */
  11365. this.morphBaseInfluence = uniform( 1 );
  11366. /**
  11367. * The update type overwritten since morph nodes are updated per object.
  11368. *
  11369. * @type {string}
  11370. */
  11371. this.updateType = NodeUpdateType.OBJECT;
  11372. }
  11373. /**
  11374. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  11375. *
  11376. * @param {NodeBuilder} builder - The current node builder.
  11377. */
  11378. setup( builder ) {
  11379. const { geometry } = builder;
  11380. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11381. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  11382. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11383. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11384. // nodes
  11385. const { texture: bufferMap, stride, size } = getEntry( geometry );
  11386. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  11387. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  11388. const width = int( size.width );
  11389. Loop( morphTargetsCount, ( { i } ) => {
  11390. const influence = float( 0 ).toVar();
  11391. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  11392. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  11393. } else {
  11394. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  11395. }
  11396. If( influence.notEqual( 0 ), () => {
  11397. if ( hasMorphPosition === true ) {
  11398. positionLocal.addAssign( getMorph( {
  11399. bufferMap,
  11400. influence,
  11401. stride,
  11402. width,
  11403. depth: i,
  11404. offset: int( 0 )
  11405. } ) );
  11406. }
  11407. if ( hasMorphNormals === true ) {
  11408. normalLocal.addAssign( getMorph( {
  11409. bufferMap,
  11410. influence,
  11411. stride,
  11412. width,
  11413. depth: i,
  11414. offset: int( 1 )
  11415. } ) );
  11416. }
  11417. } );
  11418. } );
  11419. }
  11420. /**
  11421. * Updates the state of the morphed mesh by updating the base influence.
  11422. *
  11423. * @param {NodeFrame} frame - The current node frame.
  11424. */
  11425. update( /*frame*/ ) {
  11426. const morphBaseInfluence = this.morphBaseInfluence;
  11427. if ( this.mesh.geometry.morphTargetsRelative ) {
  11428. morphBaseInfluence.value = 1;
  11429. } else {
  11430. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  11431. }
  11432. }
  11433. }
  11434. /**
  11435. * TSL function for creating a morph node.
  11436. *
  11437. * @tsl
  11438. * @function
  11439. * @param {Mesh} mesh - The mesh holding the morph targets.
  11440. * @returns {MorphNode}
  11441. */
  11442. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  11443. /**
  11444. * Base class for lighting nodes.
  11445. *
  11446. * @augments Node
  11447. */
  11448. class LightingNode extends Node {
  11449. static get type() {
  11450. return 'LightingNode';
  11451. }
  11452. /**
  11453. * Constructs a new lighting node.
  11454. */
  11455. constructor() {
  11456. super( 'vec3' );
  11457. /**
  11458. * This flag can be used for type testing.
  11459. *
  11460. * @type {boolean}
  11461. * @readonly
  11462. * @default true
  11463. */
  11464. this.isLightingNode = true;
  11465. }
  11466. }
  11467. /**
  11468. * A generic class that can be used by nodes which contribute
  11469. * ambient occlusion to the scene. E.g. an ambient occlusion map
  11470. * node can be used as input for this module. Used in {@link NodeMaterial}.
  11471. *
  11472. * @augments LightingNode
  11473. */
  11474. class AONode extends LightingNode {
  11475. static get type() {
  11476. return 'AONode';
  11477. }
  11478. /**
  11479. * Constructs a new AO node.
  11480. *
  11481. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  11482. */
  11483. constructor( aoNode = null ) {
  11484. super();
  11485. /**
  11486. * The ambient occlusion node.
  11487. *
  11488. * @type {?Node<float>}
  11489. * @default null
  11490. */
  11491. this.aoNode = aoNode;
  11492. }
  11493. setup( builder ) {
  11494. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  11495. }
  11496. }
  11497. /**
  11498. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  11499. * by adding lighting specific context data. It represents the runtime context of
  11500. * {@link LightsNode}.
  11501. *
  11502. * @augments ContextNode
  11503. */
  11504. class LightingContextNode extends ContextNode {
  11505. static get type() {
  11506. return 'LightingContextNode';
  11507. }
  11508. /**
  11509. * Constructs a new lighting context node.
  11510. *
  11511. * @param {LightsNode} lightsNode - The lights node.
  11512. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  11513. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  11514. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  11515. */
  11516. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  11517. super( lightsNode );
  11518. /**
  11519. * The current lighting model.
  11520. *
  11521. * @type {?LightingModel}
  11522. * @default null
  11523. */
  11524. this.lightingModel = lightingModel;
  11525. /**
  11526. * A backdrop node.
  11527. *
  11528. * @type {?Node<vec3>}
  11529. * @default null
  11530. */
  11531. this.backdropNode = backdropNode;
  11532. /**
  11533. * A backdrop alpha node.
  11534. *
  11535. * @type {?Node<float>}
  11536. * @default null
  11537. */
  11538. this.backdropAlphaNode = backdropAlphaNode;
  11539. this._value = null;
  11540. }
  11541. /**
  11542. * Returns a lighting context object.
  11543. *
  11544. * @return {{
  11545. * radiance: Node<vec3>,
  11546. * irradiance: Node<vec3>,
  11547. * iblIrradiance: Node<vec3>,
  11548. * ambientOcclusion: Node<float>,
  11549. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  11550. * backdrop: Node<vec3>,
  11551. * backdropAlpha: Node<float>
  11552. * }} The lighting context object.
  11553. */
  11554. getContext() {
  11555. const { backdropNode, backdropAlphaNode } = this;
  11556. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  11557. directSpecular = vec3().toVar( 'directSpecular' ),
  11558. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  11559. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  11560. const reflectedLight = {
  11561. directDiffuse,
  11562. directSpecular,
  11563. indirectDiffuse,
  11564. indirectSpecular
  11565. };
  11566. const context = {
  11567. radiance: vec3().toVar( 'radiance' ),
  11568. irradiance: vec3().toVar( 'irradiance' ),
  11569. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  11570. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  11571. reflectedLight,
  11572. backdrop: backdropNode,
  11573. backdropAlpha: backdropAlphaNode
  11574. };
  11575. return context;
  11576. }
  11577. setup( builder ) {
  11578. this.value = this._value || ( this._value = this.getContext() );
  11579. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  11580. return super.setup( builder );
  11581. }
  11582. }
  11583. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  11584. /**
  11585. * A generic class that can be used by nodes which contribute
  11586. * irradiance to the scene. E.g. a light map node can be used
  11587. * as input for this module. Used in {@link NodeMaterial}.
  11588. *
  11589. * @augments LightingNode
  11590. */
  11591. class IrradianceNode extends LightingNode {
  11592. static get type() {
  11593. return 'IrradianceNode';
  11594. }
  11595. /**
  11596. * Constructs a new irradiance node.
  11597. *
  11598. * @param {Node<vec3>} node - A node contributing irradiance.
  11599. */
  11600. constructor( node ) {
  11601. super();
  11602. /**
  11603. * A node contributing irradiance.
  11604. *
  11605. * @type {Node<vec3>}
  11606. */
  11607. this.node = node;
  11608. }
  11609. setup( builder ) {
  11610. builder.context.irradiance.addAssign( this.node );
  11611. }
  11612. }
  11613. let screenSizeVec, viewportVec;
  11614. /**
  11615. * This node provides a collection of screen related metrics.
  11616. * Depending on {@link ScreenNode#scope}, the nodes can represent
  11617. * resolution or viewport data as well as fragment or uv coordinates.
  11618. *
  11619. * @augments Node
  11620. */
  11621. class ScreenNode extends Node {
  11622. static get type() {
  11623. return 'ScreenNode';
  11624. }
  11625. /**
  11626. * Constructs a new screen node.
  11627. *
  11628. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  11629. */
  11630. constructor( scope ) {
  11631. super();
  11632. /**
  11633. * The node represents different metric depending on which scope is selected.
  11634. *
  11635. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  11636. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  11637. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  11638. * - `ScreenNode.UV`: Normalized coordinates.
  11639. *
  11640. * @type {('coordinate'|'viewport'|'size'|'uv')}
  11641. */
  11642. this.scope = scope;
  11643. /**
  11644. * This flag can be used for type testing.
  11645. *
  11646. * @type {boolean}
  11647. * @readonly
  11648. * @default true
  11649. */
  11650. this.isViewportNode = true;
  11651. }
  11652. /**
  11653. * This method is overwritten since the node type depends on the selected scope.
  11654. *
  11655. * @return {('vec2'|'vec4')} The node type.
  11656. */
  11657. getNodeType() {
  11658. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  11659. else return 'vec2';
  11660. }
  11661. /**
  11662. * This method is overwritten since the node's update type depends on the selected scope.
  11663. *
  11664. * @return {NodeUpdateType} The update type.
  11665. */
  11666. getUpdateType() {
  11667. let updateType = NodeUpdateType.NONE;
  11668. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  11669. updateType = NodeUpdateType.RENDER;
  11670. }
  11671. this.updateType = updateType;
  11672. return updateType;
  11673. }
  11674. /**
  11675. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  11676. * from the current renderer.
  11677. *
  11678. * @param {NodeFrame} frame - A reference to the current node frame.
  11679. */
  11680. update( { renderer } ) {
  11681. const renderTarget = renderer.getRenderTarget();
  11682. if ( this.scope === ScreenNode.VIEWPORT ) {
  11683. if ( renderTarget !== null ) {
  11684. viewportVec.copy( renderTarget.viewport );
  11685. } else {
  11686. renderer.getViewport( viewportVec );
  11687. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  11688. }
  11689. } else {
  11690. if ( renderTarget !== null ) {
  11691. screenSizeVec.width = renderTarget.width;
  11692. screenSizeVec.height = renderTarget.height;
  11693. } else {
  11694. renderer.getDrawingBufferSize( screenSizeVec );
  11695. }
  11696. }
  11697. }
  11698. setup( /*builder*/ ) {
  11699. const scope = this.scope;
  11700. let output = null;
  11701. if ( scope === ScreenNode.SIZE ) {
  11702. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  11703. } else if ( scope === ScreenNode.VIEWPORT ) {
  11704. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  11705. } else {
  11706. output = vec2( screenCoordinate.div( screenSize ) );
  11707. }
  11708. return output;
  11709. }
  11710. generate( builder ) {
  11711. if ( this.scope === ScreenNode.COORDINATE ) {
  11712. let coord = builder.getFragCoord();
  11713. if ( builder.isFlipY() ) {
  11714. // follow webgpu standards
  11715. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  11716. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  11717. }
  11718. return coord;
  11719. }
  11720. return super.generate( builder );
  11721. }
  11722. }
  11723. ScreenNode.COORDINATE = 'coordinate';
  11724. ScreenNode.VIEWPORT = 'viewport';
  11725. ScreenNode.SIZE = 'size';
  11726. ScreenNode.UV = 'uv';
  11727. // Screen
  11728. /**
  11729. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  11730. *
  11731. * @tsl
  11732. * @type {ScreenNode<vec2>}
  11733. */
  11734. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  11735. /**
  11736. * TSL object that represents the screen resolution in physical pixel units.
  11737. *
  11738. * @tsl
  11739. * @type {ScreenNode<vec2>}
  11740. */
  11741. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  11742. /**
  11743. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  11744. *
  11745. * @tsl
  11746. * @type {ScreenNode<vec2>}
  11747. */
  11748. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  11749. // Viewport
  11750. /**
  11751. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  11752. *
  11753. * @tsl
  11754. * @type {ScreenNode<vec4>}
  11755. */
  11756. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  11757. /**
  11758. * TSL object that represents the viewport resolution in physical pixel units.
  11759. *
  11760. * @tsl
  11761. * @type {ScreenNode<vec2>}
  11762. */
  11763. const viewportSize = viewport.zw;
  11764. /**
  11765. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  11766. *
  11767. * @tsl
  11768. * @type {ScreenNode<vec2>}
  11769. */
  11770. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  11771. /**
  11772. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  11773. *
  11774. * @tsl
  11775. * @type {ScreenNode<vec2>}
  11776. */
  11777. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  11778. // Deprecated
  11779. /**
  11780. * @deprecated since r169. Use {@link screenSize} instead.
  11781. */
  11782. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  11783. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  11784. return screenSize;
  11785. }, 'vec2' ).once() )();
  11786. /**
  11787. * @tsl
  11788. * @deprecated since r168. Use {@link screenUV} instead.
  11789. * @type {Node<vec2>}
  11790. */
  11791. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11792. console.warn( 'THREE.TSL: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  11793. return screenUV;
  11794. }, 'vec2' ).once() )();
  11795. /**
  11796. * @tsl
  11797. * @deprecated since r168. Use `screenUV.flipY()` instead.
  11798. * @type {Node<vec2>}
  11799. */
  11800. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11801. console.warn( 'THREE.TSL: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  11802. return screenUV.flipY();
  11803. }, 'vec2' ).once() )();
  11804. const _size$4 = /*@__PURE__*/ new Vector2();
  11805. /**
  11806. * A special type of texture node which represents the data of the current viewport
  11807. * as a texture. The module extracts data from the current bound framebuffer with
  11808. * a copy operation so no extra render pass is required to produce the texture data
  11809. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  11810. * variety of effects like refractive or transmissive materials.
  11811. *
  11812. * @augments TextureNode
  11813. */
  11814. class ViewportTextureNode extends TextureNode {
  11815. static get type() {
  11816. return 'ViewportTextureNode';
  11817. }
  11818. /**
  11819. * Constructs a new viewport texture node.
  11820. *
  11821. * @param {Node} [uvNode=screenUV] - The uv node.
  11822. * @param {?Node} [levelNode=null] - The level node.
  11823. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11824. */
  11825. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  11826. if ( framebufferTexture === null ) {
  11827. framebufferTexture = new FramebufferTexture();
  11828. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  11829. }
  11830. super( framebufferTexture, uvNode, levelNode );
  11831. /**
  11832. * Whether to generate mipmaps or not.
  11833. *
  11834. * @type {boolean}
  11835. * @default false
  11836. */
  11837. this.generateMipmaps = false;
  11838. /**
  11839. * This flag can be used for type testing.
  11840. *
  11841. * @type {boolean}
  11842. * @readonly
  11843. * @default true
  11844. */
  11845. this.isOutputTextureNode = true;
  11846. /**
  11847. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  11848. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  11849. *
  11850. * @type {string}
  11851. * @default 'frame'
  11852. */
  11853. this.updateBeforeType = NodeUpdateType.FRAME;
  11854. }
  11855. updateBefore( frame ) {
  11856. const renderer = frame.renderer;
  11857. renderer.getDrawingBufferSize( _size$4 );
  11858. //
  11859. const framebufferTexture = this.value;
  11860. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  11861. framebufferTexture.image.width = _size$4.width;
  11862. framebufferTexture.image.height = _size$4.height;
  11863. framebufferTexture.needsUpdate = true;
  11864. }
  11865. //
  11866. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  11867. framebufferTexture.generateMipmaps = this.generateMipmaps;
  11868. renderer.copyFramebufferToTexture( framebufferTexture );
  11869. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  11870. }
  11871. clone() {
  11872. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  11873. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  11874. return viewportTextureNode;
  11875. }
  11876. }
  11877. /**
  11878. * TSL function for creating a viewport texture node.
  11879. *
  11880. * @tsl
  11881. * @function
  11882. * @param {?Node} [uvNode=screenUV] - The uv node.
  11883. * @param {?Node} [levelNode=null] - The level node.
  11884. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11885. * @returns {ViewportTextureNode}
  11886. */
  11887. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  11888. /**
  11889. * TSL function for creating a viewport texture node with enabled mipmap generation.
  11890. *
  11891. * @tsl
  11892. * @function
  11893. * @param {?Node} [uvNode=screenUV] - The uv node.
  11894. * @param {?Node} [levelNode=null] - The level node.
  11895. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  11896. * @returns {ViewportTextureNode}
  11897. */
  11898. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  11899. let sharedDepthbuffer = null;
  11900. /**
  11901. * Represents the depth of the current viewport as a texture. This module
  11902. * can be used in combination with viewport texture to achieve effects
  11903. * that require depth evaluation.
  11904. *
  11905. * @augments ViewportTextureNode
  11906. */
  11907. class ViewportDepthTextureNode extends ViewportTextureNode {
  11908. static get type() {
  11909. return 'ViewportDepthTextureNode';
  11910. }
  11911. /**
  11912. * Constructs a new viewport depth texture node.
  11913. *
  11914. * @param {Node} [uvNode=screenUV] - The uv node.
  11915. * @param {?Node} [levelNode=null] - The level node.
  11916. */
  11917. constructor( uvNode = screenUV, levelNode = null ) {
  11918. if ( sharedDepthbuffer === null ) {
  11919. sharedDepthbuffer = new DepthTexture();
  11920. }
  11921. super( uvNode, levelNode, sharedDepthbuffer );
  11922. }
  11923. }
  11924. /**
  11925. * TSL function for a viewport depth texture node.
  11926. *
  11927. * @tsl
  11928. * @function
  11929. * @param {?Node} [uvNode=screenUV] - The uv node.
  11930. * @param {?Node} [levelNode=null] - The level node.
  11931. * @returns {ViewportDepthTextureNode}
  11932. */
  11933. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  11934. /**
  11935. * This node offers a collection of features in context of the depth logic in the fragment shader.
  11936. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  11937. * fragment or for depth evaluation purposes.
  11938. *
  11939. * @augments Node
  11940. */
  11941. class ViewportDepthNode extends Node {
  11942. static get type() {
  11943. return 'ViewportDepthNode';
  11944. }
  11945. /**
  11946. * Constructs a new viewport depth node.
  11947. *
  11948. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  11949. * @param {?Node} [valueNode=null] - The value node.
  11950. */
  11951. constructor( scope, valueNode = null ) {
  11952. super( 'float' );
  11953. /**
  11954. * The node behaves differently depending on which scope is selected.
  11955. *
  11956. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  11957. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  11958. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  11959. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  11960. *
  11961. * @type {('depth'|'depthBase'|'linearDepth')}
  11962. */
  11963. this.scope = scope;
  11964. /**
  11965. * Can be used to define a custom depth value.
  11966. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  11967. *
  11968. * @type {?Node}
  11969. * @default null
  11970. */
  11971. this.valueNode = valueNode;
  11972. /**
  11973. * This flag can be used for type testing.
  11974. *
  11975. * @type {boolean}
  11976. * @readonly
  11977. * @default true
  11978. */
  11979. this.isViewportDepthNode = true;
  11980. }
  11981. generate( builder ) {
  11982. const { scope } = this;
  11983. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11984. return builder.getFragDepth();
  11985. }
  11986. return super.generate( builder );
  11987. }
  11988. setup( { camera } ) {
  11989. const { scope } = this;
  11990. const value = this.valueNode;
  11991. let node = null;
  11992. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  11993. if ( value !== null ) {
  11994. node = depthBase().assign( value );
  11995. }
  11996. } else if ( scope === ViewportDepthNode.DEPTH ) {
  11997. if ( camera.isPerspectiveCamera ) {
  11998. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  11999. } else {
  12000. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12001. }
  12002. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12003. if ( value !== null ) {
  12004. if ( camera.isPerspectiveCamera ) {
  12005. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12006. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12007. } else {
  12008. node = value;
  12009. }
  12010. } else {
  12011. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12012. }
  12013. }
  12014. return node;
  12015. }
  12016. }
  12017. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12018. ViewportDepthNode.DEPTH = 'depth';
  12019. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12020. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12021. /**
  12022. * TSL function for converting a viewZ value to an orthographic depth value.
  12023. *
  12024. * @tsl
  12025. * @function
  12026. * @param {Node<float>} viewZ - The viewZ node.
  12027. * @param {Node<float>} near - The camera's near value.
  12028. * @param {Node<float>} far - The camera's far value.
  12029. * @returns {Node<float>}
  12030. */
  12031. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12032. /**
  12033. * TSL function for converting an orthographic depth value to a viewZ value.
  12034. *
  12035. * @tsl
  12036. * @function
  12037. * @param {Node<float>} depth - The orthographic depth.
  12038. * @param {Node<float>} near - The camera's near value.
  12039. * @param {Node<float>} far - The camera's far value.
  12040. * @returns {Node<float>}
  12041. */
  12042. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12043. /**
  12044. * TSL function for converting a viewZ value to a perspective depth value.
  12045. *
  12046. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12047. *
  12048. * @tsl
  12049. * @function
  12050. * @param {Node<float>} viewZ - The viewZ node.
  12051. * @param {Node<float>} near - The camera's near value.
  12052. * @param {Node<float>} far - The camera's far value.
  12053. * @returns {Node<float>}
  12054. */
  12055. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12056. /**
  12057. * TSL function for converting a perspective depth value to a viewZ value.
  12058. *
  12059. * @tsl
  12060. * @function
  12061. * @param {Node<float>} depth - The perspective depth.
  12062. * @param {Node<float>} near - The camera's near value.
  12063. * @param {Node<float>} far - The camera's far value.
  12064. * @returns {Node<float>}
  12065. */
  12066. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12067. /**
  12068. * TSL function for converting a viewZ value to a logarithmic depth value.
  12069. *
  12070. * @tsl
  12071. * @function
  12072. * @param {Node<float>} viewZ - The viewZ node.
  12073. * @param {Node<float>} near - The camera's near value.
  12074. * @param {Node<float>} far - The camera's far value.
  12075. * @returns {Node<float>}
  12076. */
  12077. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12078. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12079. // The final logarithmic depth formula used here is adapted from one described in an
  12080. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12081. // which was an improvement upon an earlier formula one described in an
  12082. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12083. // Ulrich's formula is the following:
  12084. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12085. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12086. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12087. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12088. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12089. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12090. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12091. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12092. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12093. // Outerra eventually made another improvement to their original "C-constant" variant,
  12094. // but it still does not incorporate the camera near plane (for this version,
  12095. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12096. // Here we make 4 changes to Ulrich's formula:
  12097. // 1. Clamp the camera near plane so we don't divide by 0.
  12098. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12099. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12100. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12101. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12102. // so we do the same here, hence the 'viewZ.negate()' call.
  12103. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12104. near = near.max( 1e-6 ).toVar();
  12105. const numerator = log2( viewZ.negate().div( near ) );
  12106. const denominator = log2( far.div( near ) );
  12107. return numerator.div( denominator );
  12108. };
  12109. /**
  12110. * TSL function for converting a logarithmic depth value to a viewZ value.
  12111. *
  12112. * @tsl
  12113. * @function
  12114. * @param {Node<float>} depth - The logarithmic depth.
  12115. * @param {Node<float>} near - The camera's near value.
  12116. * @param {Node<float>} far - The camera's far value.
  12117. * @returns {Node<float>}
  12118. */
  12119. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12120. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12121. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12122. // a negative viewZ).
  12123. const exponent = depth.mul( log( far.div( near ) ) );
  12124. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12125. };
  12126. /**
  12127. * TSL function for defining a value for the current fragment's depth.
  12128. *
  12129. * @tsl
  12130. * @function
  12131. * @param {Node<float>} value - The depth value to set.
  12132. * @returns {ViewportDepthNode<float>}
  12133. */
  12134. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12135. /**
  12136. * TSL object that represents the depth value for the current fragment.
  12137. *
  12138. * @tsl
  12139. * @type {ViewportDepthNode}
  12140. */
  12141. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12142. /**
  12143. * TSL function for converting a perspective depth value to linear depth.
  12144. *
  12145. * @tsl
  12146. * @function
  12147. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12148. * @returns {ViewportDepthNode<float>}
  12149. */
  12150. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12151. /**
  12152. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12153. *
  12154. * @tsl
  12155. * @type {ViewportDepthNode}
  12156. */
  12157. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12158. depth.assign = ( value ) => depthBase( value );
  12159. /**
  12160. * This node is used in {@link NodeMaterial} to setup the clipping
  12161. * which can happen hardware-accelerated (if supported) and optionally
  12162. * use alpha-to-coverage for anti-aliasing clipped edges.
  12163. *
  12164. * @augments Node
  12165. */
  12166. class ClippingNode extends Node {
  12167. static get type() {
  12168. return 'ClippingNode';
  12169. }
  12170. /**
  12171. * Constructs a new clipping node.
  12172. *
  12173. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12174. * the selected scope influences the behavior of the node and what type of code is generated.
  12175. */
  12176. constructor( scope = ClippingNode.DEFAULT ) {
  12177. super();
  12178. /**
  12179. * The node's scope. Similar to other nodes, the selected scope influences
  12180. * the behavior of the node and what type of code is generated.
  12181. *
  12182. * @type {('default'|'hardware'|'alphaToCoverage')}
  12183. */
  12184. this.scope = scope;
  12185. }
  12186. /**
  12187. * Setups the node depending on the selected scope.
  12188. *
  12189. * @param {NodeBuilder} builder - The current node builder.
  12190. * @return {Node} The result node.
  12191. */
  12192. setup( builder ) {
  12193. super.setup( builder );
  12194. const clippingContext = builder.clippingContext;
  12195. const { intersectionPlanes, unionPlanes } = clippingContext;
  12196. this.hardwareClipping = builder.material.hardwareClipping;
  12197. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12198. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12199. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12200. return this.setupHardwareClipping( unionPlanes, builder );
  12201. } else {
  12202. return this.setupDefault( intersectionPlanes, unionPlanes );
  12203. }
  12204. }
  12205. /**
  12206. * Setups alpha to coverage.
  12207. *
  12208. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12209. * @param {Array<Vector4>} unionPlanes - The union planes.
  12210. * @return {Node} The result node.
  12211. */
  12212. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12213. return Fn( () => {
  12214. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12215. const distanceGradient = float().toVar( 'distanceToGradient' );
  12216. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12217. const numUnionPlanes = unionPlanes.length;
  12218. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12219. const clippingPlanes = uniformArray( unionPlanes );
  12220. Loop( numUnionPlanes, ( { i } ) => {
  12221. const plane = clippingPlanes.element( i );
  12222. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12223. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12224. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  12225. } );
  12226. }
  12227. const numIntersectionPlanes = intersectionPlanes.length;
  12228. if ( numIntersectionPlanes > 0 ) {
  12229. const clippingPlanes = uniformArray( intersectionPlanes );
  12230. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  12231. Loop( numIntersectionPlanes, ( { i } ) => {
  12232. const plane = clippingPlanes.element( i );
  12233. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12234. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12235. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  12236. } );
  12237. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  12238. }
  12239. diffuseColor.a.mulAssign( clipOpacity );
  12240. diffuseColor.a.equal( 0.0 ).discard();
  12241. } )();
  12242. }
  12243. /**
  12244. * Setups the default clipping.
  12245. *
  12246. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12247. * @param {Array<Vector4>} unionPlanes - The union planes.
  12248. * @return {Node} The result node.
  12249. */
  12250. setupDefault( intersectionPlanes, unionPlanes ) {
  12251. return Fn( () => {
  12252. const numUnionPlanes = unionPlanes.length;
  12253. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12254. const clippingPlanes = uniformArray( unionPlanes );
  12255. Loop( numUnionPlanes, ( { i } ) => {
  12256. const plane = clippingPlanes.element( i );
  12257. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  12258. } );
  12259. }
  12260. const numIntersectionPlanes = intersectionPlanes.length;
  12261. if ( numIntersectionPlanes > 0 ) {
  12262. const clippingPlanes = uniformArray( intersectionPlanes );
  12263. const clipped = bool( true ).toVar( 'clipped' );
  12264. Loop( numIntersectionPlanes, ( { i } ) => {
  12265. const plane = clippingPlanes.element( i );
  12266. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  12267. } );
  12268. clipped.discard();
  12269. }
  12270. } )();
  12271. }
  12272. /**
  12273. * Setups hardware clipping.
  12274. *
  12275. * @param {Array<Vector4>} unionPlanes - The union planes.
  12276. * @param {NodeBuilder} builder - The current node builder.
  12277. * @return {Node} The result node.
  12278. */
  12279. setupHardwareClipping( unionPlanes, builder ) {
  12280. const numUnionPlanes = unionPlanes.length;
  12281. builder.enableHardwareClipping( numUnionPlanes );
  12282. return Fn( () => {
  12283. const clippingPlanes = uniformArray( unionPlanes );
  12284. const hw_clip_distances = builtin( builder.getClipDistance() );
  12285. Loop( numUnionPlanes, ( { i } ) => {
  12286. const plane = clippingPlanes.element( i );
  12287. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  12288. hw_clip_distances.element( i ).assign( distance );
  12289. } );
  12290. } )();
  12291. }
  12292. }
  12293. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  12294. ClippingNode.DEFAULT = 'default';
  12295. ClippingNode.HARDWARE = 'hardware';
  12296. /**
  12297. * TSL function for setting up the default clipping logic.
  12298. *
  12299. * @tsl
  12300. * @function
  12301. * @returns {ClippingNode}
  12302. */
  12303. const clipping = () => nodeObject( new ClippingNode() );
  12304. /**
  12305. * TSL function for setting up alpha to coverage.
  12306. *
  12307. * @tsl
  12308. * @function
  12309. * @returns {ClippingNode}
  12310. */
  12311. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  12312. /**
  12313. * TSL function for setting up hardware-based clipping.
  12314. *
  12315. * @tsl
  12316. * @function
  12317. * @returns {ClippingNode}
  12318. */
  12319. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  12320. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  12321. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  12322. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12323. 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 ) ) ) ) ) );
  12324. } );
  12325. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12326. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  12327. } );
  12328. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  12329. // Find the discretized derivatives of our coordinates
  12330. const maxDeriv = max$1(
  12331. length( dFdx( position.xyz ) ),
  12332. length( dFdy( position.xyz ) )
  12333. );
  12334. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  12335. // Find two nearest log-discretized noise scales
  12336. const pixScales = vec2(
  12337. exp2( floor( log2( pixScale ) ) ),
  12338. exp2( ceil( log2( pixScale ) ) )
  12339. );
  12340. // Compute alpha thresholds at our two noise scales
  12341. const alpha = vec2(
  12342. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  12343. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  12344. );
  12345. // Factor to interpolate lerp with
  12346. const lerpFactor = fract( log2( pixScale ) );
  12347. // Interpolate alpha threshold from noise at two scales
  12348. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  12349. // Pass into CDF to compute uniformly distrib threshold
  12350. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  12351. const cases = vec3(
  12352. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  12353. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  12354. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  12355. // Find our final, uniformly distributed alpha threshold (ατ)
  12356. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  12357. // Avoids ατ == 0. Could also do ατ =1-ατ
  12358. return clamp( threshold, 1.0e-6, 1.0 );
  12359. } ).setLayout( {
  12360. name: 'getAlphaHashThreshold',
  12361. type: 'float',
  12362. inputs: [
  12363. { name: 'position', type: 'vec3' }
  12364. ]
  12365. } );
  12366. /**
  12367. * An attribute node for representing vertex colors.
  12368. *
  12369. * @augments AttributeNode
  12370. */
  12371. class VertexColorNode extends AttributeNode {
  12372. static get type() {
  12373. return 'VertexColorNode';
  12374. }
  12375. /**
  12376. * Constructs a new vertex color node.
  12377. *
  12378. * @param {number} index - The attribute index.
  12379. */
  12380. constructor( index ) {
  12381. super( null, 'vec4' );
  12382. /**
  12383. * This flag can be used for type testing.
  12384. *
  12385. * @type {boolean}
  12386. * @readonly
  12387. * @default true
  12388. */
  12389. this.isVertexColorNode = true;
  12390. /**
  12391. * The attribute index to enable more than one sets of vertex colors.
  12392. *
  12393. * @type {number}
  12394. * @default 0
  12395. */
  12396. this.index = index;
  12397. }
  12398. /**
  12399. * Overwrites the default implementation by honoring the attribute index.
  12400. *
  12401. * @param {NodeBuilder} builder - The current node builder.
  12402. * @return {string} The attribute name.
  12403. */
  12404. getAttributeName( /*builder*/ ) {
  12405. const index = this.index;
  12406. return 'color' + ( index > 0 ? index : '' );
  12407. }
  12408. generate( builder ) {
  12409. const attributeName = this.getAttributeName( builder );
  12410. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12411. let result;
  12412. if ( geometryAttribute === true ) {
  12413. result = super.generate( builder );
  12414. } else {
  12415. // Vertex color fallback should be white
  12416. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12417. }
  12418. return result;
  12419. }
  12420. serialize( data ) {
  12421. super.serialize( data );
  12422. data.index = this.index;
  12423. }
  12424. deserialize( data ) {
  12425. super.deserialize( data );
  12426. this.index = data.index;
  12427. }
  12428. }
  12429. /**
  12430. * TSL function for creating a reference node.
  12431. *
  12432. * @tsl
  12433. * @function
  12434. * @param {number} [index=0] - The attribute index.
  12435. * @returns {VertexColorNode}
  12436. */
  12437. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  12438. /**
  12439. * Base class for all node materials.
  12440. *
  12441. * @augments Material
  12442. */
  12443. class NodeMaterial extends Material {
  12444. static get type() {
  12445. return 'NodeMaterial';
  12446. }
  12447. /**
  12448. * Represents the type of the node material.
  12449. *
  12450. * @type {string}
  12451. */
  12452. get type() {
  12453. return this.constructor.type;
  12454. }
  12455. set type( _value ) { /* */ }
  12456. /**
  12457. * Constructs a new node material.
  12458. */
  12459. constructor() {
  12460. super();
  12461. /**
  12462. * This flag can be used for type testing.
  12463. *
  12464. * @type {boolean}
  12465. * @readonly
  12466. * @default true
  12467. */
  12468. this.isNodeMaterial = true;
  12469. /**
  12470. * Whether this material is affected by fog or not.
  12471. *
  12472. * @type {boolean}
  12473. * @default true
  12474. */
  12475. this.fog = true;
  12476. /**
  12477. * Whether this material is affected by lights or not.
  12478. *
  12479. * @type {boolean}
  12480. * @default false
  12481. */
  12482. this.lights = false;
  12483. /**
  12484. * Whether this material uses hardware clipping or not.
  12485. * This property is managed by the engine and should not be
  12486. * modified by apps.
  12487. *
  12488. * @type {boolean}
  12489. * @default false
  12490. */
  12491. this.hardwareClipping = false;
  12492. /**
  12493. * Node materials which set their `lights` property to `true`
  12494. * are affected by all lights of the scene. Sometimes selective
  12495. * lighting is wanted which means only _some_ lights in the scene
  12496. * affect a material. This can be achieved by creating an instance
  12497. * of {@link LightsNode} with a list of selective
  12498. * lights and assign the node to this property.
  12499. *
  12500. * ```js
  12501. * const customLightsNode = lights( [ light1, light2 ] );
  12502. * material.lightsNode = customLightsNode;
  12503. * ```
  12504. *
  12505. * @type {?LightsNode}
  12506. * @default null
  12507. */
  12508. this.lightsNode = null;
  12509. /**
  12510. * The environment of node materials can be defined by an environment
  12511. * map assigned to the `envMap` property or by `Scene.environment`
  12512. * if the node material is a PBR material. This node property allows to overwrite
  12513. * the default behavior and define the environment with a custom node.
  12514. *
  12515. * ```js
  12516. * material.envNode = pmremTexture( renderTarget.texture );
  12517. * ```
  12518. *
  12519. * @type {?Node<vec3>}
  12520. * @default null
  12521. */
  12522. this.envNode = null;
  12523. /**
  12524. * The lighting of node materials might be influenced by ambient occlusion.
  12525. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  12526. * and the respective `aoMapIntensity`. This node property allows to overwrite
  12527. * the default and define the ambient occlusion with a custom node instead.
  12528. *
  12529. * If you don't want to overwrite the diffuse color but modify the existing
  12530. * values instead, use {@link materialAO}.
  12531. *
  12532. * @type {?Node<float>}
  12533. * @default null
  12534. */
  12535. this.aoNode = null;
  12536. /**
  12537. * The diffuse color of node materials is by default inferred from the
  12538. * `color` and `map` properties. This node property allows to overwrite the default
  12539. * and define the diffuse color with a node instead.
  12540. *
  12541. * ```js
  12542. * material.colorNode = color( 0xff0000 ); // define red color
  12543. * ```
  12544. *
  12545. * If you don't want to overwrite the diffuse color but modify the existing
  12546. * values instead, use {@link materialColor}.
  12547. *
  12548. * ```js
  12549. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  12550. * ```
  12551. *
  12552. * @type {?Node<vec3>}
  12553. * @default null
  12554. */
  12555. this.colorNode = null;
  12556. /**
  12557. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  12558. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  12559. * and define the normals with a node instead.
  12560. *
  12561. * If you don't want to overwrite the normals but modify the existing values instead,
  12562. * use {@link materialNormal}.
  12563. *
  12564. * @type {?Node<vec3>}
  12565. * @default null
  12566. */
  12567. this.normalNode = null;
  12568. /**
  12569. * The opacity of node materials is by default inferred from the `opacity`
  12570. * and `alphaMap` properties. This node property allows to overwrite the default
  12571. * and define the opacity with a node instead.
  12572. *
  12573. * If you don't want to overwrite the normals but modify the existing
  12574. * value instead, use {@link materialOpacity}.
  12575. *
  12576. * @type {?Node<float>}
  12577. * @default null
  12578. */
  12579. this.opacityNode = null;
  12580. /**
  12581. * This node can be used to implement a variety of filter-like effects. The idea is
  12582. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  12583. * to create an arbitrary effect and then assign the node composition to this property.
  12584. * Everything behind the object using this material will now be affected by a filter.
  12585. *
  12586. * ```js
  12587. * const material = new NodeMaterial()
  12588. * material.transparent = true;
  12589. *
  12590. * // everything behind the object will be monochromatic
  12591. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  12592. * ```
  12593. *
  12594. * Backdrop computations are part of the lighting so only lit materials can use this property.
  12595. *
  12596. * @type {?Node<vec3>}
  12597. * @default null
  12598. */
  12599. this.backdropNode = null;
  12600. /**
  12601. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  12602. *
  12603. * @type {?Node<float>}
  12604. * @default null
  12605. */
  12606. this.backdropAlphaNode = null;
  12607. /**
  12608. * The alpha test of node materials is by default inferred from the `alphaTest`
  12609. * property. This node property allows to overwrite the default and define the
  12610. * alpha test with a node instead.
  12611. *
  12612. * If you don't want to overwrite the alpha test but modify the existing
  12613. * value instead, use {@link materialAlphaTest}.
  12614. *
  12615. * @type {?Node<float>}
  12616. * @default null
  12617. */
  12618. this.alphaTestNode = null;
  12619. /**
  12620. * The local vertex positions are computed based on multiple factors like the
  12621. * attribute data, morphing or skinning. This node property allows to overwrite
  12622. * the default and define local vertex positions with nodes instead.
  12623. *
  12624. * If you don't want to overwrite the vertex positions but modify the existing
  12625. * values instead, use {@link positionLocal}.
  12626. *
  12627. *```js
  12628. * material.positionNode = positionLocal.add( displace );
  12629. * ```
  12630. *
  12631. * @type {?Node<vec3>}
  12632. * @default null
  12633. */
  12634. this.positionNode = null;
  12635. /**
  12636. * This node property is intended for logic which modifies geometry data once or per animation step.
  12637. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  12638. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  12639. * can be implemented.
  12640. *
  12641. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  12642. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  12643. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  12644. * eventually assigned to `geometryNode`.
  12645. *
  12646. * @type {?Function}
  12647. * @default null
  12648. */
  12649. this.geometryNode = null;
  12650. /**
  12651. * Allows to overwrite depth values in the fragment shader.
  12652. *
  12653. * @type {?Node<float>}
  12654. * @default null
  12655. */
  12656. this.depthNode = null;
  12657. /**
  12658. * Allows to overwrite the position used for shadow map rendering which
  12659. * is by default {@link positionWorld}, the vertex position
  12660. * in world space.
  12661. *
  12662. * @type {?Node<float>}
  12663. * @default null
  12664. */
  12665. this.receivedShadowPositionNode = null;
  12666. /**
  12667. * Allows to overwrite the geometry position used for shadow map projection which
  12668. * is by default {@link positionLocal}, the vertex position in local space.
  12669. *
  12670. * @type {?Node<float>}
  12671. * @default null
  12672. */
  12673. this.castShadowPositionNode = null;
  12674. /**
  12675. * This node can be used to influence how an object using this node material
  12676. * receive shadows.
  12677. *
  12678. * ```js
  12679. * const totalShadows = float( 1 ).toVar();
  12680. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  12681. * totalShadows.mulAssign( shadow );
  12682. * //return float( 1 ); // bypass received shadows
  12683. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  12684. * } );
  12685. *
  12686. * @type {?(Function|FunctionNode<vec4>)}
  12687. * @default null
  12688. */
  12689. this.receivedShadowNode = null;
  12690. /**
  12691. * This node can be used to influence how an object using this node material
  12692. * casts shadows. To apply a color to shadows, you can simply do:
  12693. *
  12694. * ```js
  12695. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  12696. * ```
  12697. *
  12698. * Which can be nice to fake colored shadows of semi-transparent objects. It
  12699. * is also common to use the property with `Fn` function so checks are performed
  12700. * per fragment.
  12701. *
  12702. * ```js
  12703. * materialCustomShadow.castShadowNode = Fn( () => {
  12704. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  12705. * return materialColor;
  12706. * } )();
  12707. * ```
  12708. *
  12709. * @type {?Node<vec4>}
  12710. * @default null
  12711. */
  12712. this.castShadowNode = null;
  12713. /**
  12714. * This node can be used to define the final output of the material.
  12715. *
  12716. * TODO: Explain the differences to `fragmentNode`.
  12717. *
  12718. * @type {?Node<vec4>}
  12719. * @default null
  12720. */
  12721. this.outputNode = null;
  12722. /**
  12723. * MRT configuration is done on renderer or pass level. This node allows to
  12724. * overwrite what values are written into MRT targets on material level. This
  12725. * can be useful for implementing selective FX features that should only affect
  12726. * specific objects.
  12727. *
  12728. * @type {?MRTNode}
  12729. * @default null
  12730. */
  12731. this.mrtNode = null;
  12732. /**
  12733. * This node property can be used if you need complete freedom in implementing
  12734. * the fragment shader. Assigning a node will replace the built-in material
  12735. * logic used in the fragment stage.
  12736. *
  12737. * @type {?Node<vec4>}
  12738. * @default null
  12739. */
  12740. this.fragmentNode = null;
  12741. /**
  12742. * This node property can be used if you need complete freedom in implementing
  12743. * the vertex shader. Assigning a node will replace the built-in material logic
  12744. * used in the vertex stage.
  12745. *
  12746. * @type {?Node<vec4>}
  12747. * @default null
  12748. */
  12749. this.vertexNode = null;
  12750. // Deprecated properties
  12751. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  12752. get: () => {
  12753. return this.receivedShadowPositionNode;
  12754. },
  12755. set: ( value ) => {
  12756. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  12757. this.receivedShadowPositionNode = value;
  12758. }
  12759. } );
  12760. }
  12761. /**
  12762. * Allows to define a custom cache key that influence the material key computation
  12763. * for render objects.
  12764. *
  12765. * @return {string} The custom cache key.
  12766. */
  12767. customProgramCacheKey() {
  12768. return this.type + getCacheKey$1( this );
  12769. }
  12770. /**
  12771. * Builds this material with the given node builder.
  12772. *
  12773. * @param {NodeBuilder} builder - The current node builder.
  12774. */
  12775. build( builder ) {
  12776. this.setup( builder );
  12777. }
  12778. /**
  12779. * Setups a node material observer with the given builder.
  12780. *
  12781. * @param {NodeBuilder} builder - The current node builder.
  12782. * @return {NodeMaterialObserver} The node material observer.
  12783. */
  12784. setupObserver( builder ) {
  12785. return new NodeMaterialObserver( builder );
  12786. }
  12787. /**
  12788. * Setups the vertex and fragment stage of this node material.
  12789. *
  12790. * @param {NodeBuilder} builder - The current node builder.
  12791. */
  12792. setup( builder ) {
  12793. builder.context.setupNormal = () => this.setupNormal( builder );
  12794. builder.context.setupPositionView = () => this.setupPositionView( builder );
  12795. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  12796. const renderer = builder.renderer;
  12797. const renderTarget = renderer.getRenderTarget();
  12798. // < VERTEX STAGE >
  12799. builder.addStack();
  12800. const vertexNode = this.vertexNode || this.setupVertex( builder );
  12801. builder.stack.outputNode = vertexNode;
  12802. this.setupHardwareClipping( builder );
  12803. if ( this.geometryNode !== null ) {
  12804. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  12805. }
  12806. builder.addFlow( 'vertex', builder.removeStack() );
  12807. // < FRAGMENT STAGE >
  12808. builder.addStack();
  12809. let resultNode;
  12810. const clippingNode = this.setupClipping( builder );
  12811. if ( this.depthWrite === true || this.depthTest === true ) {
  12812. // only write depth if depth buffer is configured
  12813. if ( renderTarget !== null ) {
  12814. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  12815. } else {
  12816. if ( renderer.depth === true ) this.setupDepth( builder );
  12817. }
  12818. }
  12819. if ( this.fragmentNode === null ) {
  12820. this.setupDiffuseColor( builder );
  12821. this.setupVariants( builder );
  12822. const outgoingLightNode = this.setupLighting( builder );
  12823. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  12824. // force unsigned floats - useful for RenderTargets
  12825. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  12826. resultNode = this.setupOutput( builder, basicOutput );
  12827. // OUTPUT NODE
  12828. output.assign( resultNode );
  12829. //
  12830. const isCustomOutput = this.outputNode !== null;
  12831. if ( isCustomOutput ) resultNode = this.outputNode;
  12832. // MRT
  12833. if ( renderTarget !== null ) {
  12834. const mrt = renderer.getMRT();
  12835. const materialMRT = this.mrtNode;
  12836. if ( mrt !== null ) {
  12837. if ( isCustomOutput ) output.assign( resultNode );
  12838. resultNode = mrt;
  12839. if ( materialMRT !== null ) {
  12840. resultNode = mrt.merge( materialMRT );
  12841. }
  12842. } else if ( materialMRT !== null ) {
  12843. resultNode = materialMRT;
  12844. }
  12845. }
  12846. } else {
  12847. let fragmentNode = this.fragmentNode;
  12848. if ( fragmentNode.isOutputStructNode !== true ) {
  12849. fragmentNode = vec4( fragmentNode );
  12850. }
  12851. resultNode = this.setupOutput( builder, fragmentNode );
  12852. }
  12853. builder.stack.outputNode = resultNode;
  12854. builder.addFlow( 'fragment', builder.removeStack() );
  12855. // < OBSERVER >
  12856. builder.observer = this.setupObserver( builder );
  12857. }
  12858. /**
  12859. * Setups the clipping node.
  12860. *
  12861. * @param {NodeBuilder} builder - The current node builder.
  12862. * @return {ClippingNode} The clipping node.
  12863. */
  12864. setupClipping( builder ) {
  12865. if ( builder.clippingContext === null ) return null;
  12866. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  12867. let result = null;
  12868. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  12869. const samples = builder.renderer.samples;
  12870. if ( this.alphaToCoverage && samples > 1 ) {
  12871. // to be added to flow when the color/alpha value has been determined
  12872. result = clippingAlpha();
  12873. } else {
  12874. builder.stack.add( clipping() );
  12875. }
  12876. }
  12877. return result;
  12878. }
  12879. /**
  12880. * Setups the hardware clipping if available on the current device.
  12881. *
  12882. * @param {NodeBuilder} builder - The current node builder.
  12883. */
  12884. setupHardwareClipping( builder ) {
  12885. this.hardwareClipping = false;
  12886. if ( builder.clippingContext === null ) return;
  12887. const candidateCount = builder.clippingContext.unionPlanes.length;
  12888. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  12889. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  12890. builder.stack.add( hardwareClipping() );
  12891. this.hardwareClipping = true;
  12892. }
  12893. return;
  12894. }
  12895. /**
  12896. * Setups the depth of this material.
  12897. *
  12898. * @param {NodeBuilder} builder - The current node builder.
  12899. */
  12900. setupDepth( builder ) {
  12901. const { renderer, camera } = builder;
  12902. // Depth
  12903. let depthNode = this.depthNode;
  12904. if ( depthNode === null ) {
  12905. const mrt = renderer.getMRT();
  12906. if ( mrt && mrt.has( 'depth' ) ) {
  12907. depthNode = mrt.get( 'depth' );
  12908. } else if ( renderer.logarithmicDepthBuffer === true ) {
  12909. if ( camera.isPerspectiveCamera ) {
  12910. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  12911. } else {
  12912. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12913. }
  12914. }
  12915. }
  12916. if ( depthNode !== null ) {
  12917. depth.assign( depthNode ).toStack();
  12918. }
  12919. }
  12920. /**
  12921. * Setups the position node in view space. This method exists
  12922. * so derived node materials can modify the implementation e.g. sprite materials.
  12923. *
  12924. * @param {NodeBuilder} builder - The current node builder.
  12925. * @return {Node<vec3>} The position in view space.
  12926. */
  12927. setupPositionView( /*builder*/ ) {
  12928. return modelViewMatrix.mul( positionLocal ).xyz;
  12929. }
  12930. /**
  12931. * Setups the position in clip space.
  12932. *
  12933. * @param {NodeBuilder} builder - The current node builder.
  12934. * @return {Node<vec4>} The position in view space.
  12935. */
  12936. setupModelViewProjection( /*builder*/ ) {
  12937. return cameraProjectionMatrix.mul( positionView );
  12938. }
  12939. /**
  12940. * Setups the logic for the vertex stage.
  12941. *
  12942. * @param {NodeBuilder} builder - The current node builder.
  12943. * @return {Node<vec4>} The position in clip space.
  12944. */
  12945. setupVertex( builder ) {
  12946. builder.addStack();
  12947. this.setupPosition( builder );
  12948. builder.context.vertex = builder.removeStack();
  12949. return modelViewProjection;
  12950. }
  12951. /**
  12952. * Setups the computation of the position in local space.
  12953. *
  12954. * @param {NodeBuilder} builder - The current node builder.
  12955. * @return {Node<vec3>} The position in local space.
  12956. */
  12957. setupPosition( builder ) {
  12958. const { object, geometry } = builder;
  12959. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  12960. morphReference( object ).toStack();
  12961. }
  12962. if ( object.isSkinnedMesh === true ) {
  12963. skinning( object ).toStack();
  12964. }
  12965. if ( this.displacementMap ) {
  12966. const displacementMap = materialReference( 'displacementMap', 'texture' );
  12967. const displacementScale = materialReference( 'displacementScale', 'float' );
  12968. const displacementBias = materialReference( 'displacementBias', 'float' );
  12969. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  12970. }
  12971. if ( object.isBatchedMesh ) {
  12972. batch( object ).toStack();
  12973. }
  12974. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  12975. instancedMesh( object ).toStack();
  12976. }
  12977. if ( this.positionNode !== null ) {
  12978. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  12979. }
  12980. return positionLocal;
  12981. }
  12982. /**
  12983. * Setups the computation of the material's diffuse color.
  12984. *
  12985. * @param {NodeBuilder} builder - The current node builder.
  12986. * @param {BufferGeometry} geometry - The geometry.
  12987. */
  12988. setupDiffuseColor( { object, geometry } ) {
  12989. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  12990. // VERTEX COLORS
  12991. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  12992. colorNode = colorNode.mul( vertexColor() );
  12993. }
  12994. // Instanced colors
  12995. if ( object.instanceColor ) {
  12996. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  12997. colorNode = instanceColor.mul( colorNode );
  12998. }
  12999. if ( object.isBatchedMesh && object._colorsTexture ) {
  13000. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13001. colorNode = batchColor.mul( colorNode );
  13002. }
  13003. // COLOR
  13004. diffuseColor.assign( colorNode );
  13005. // OPACITY
  13006. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13007. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13008. // ALPHA TEST
  13009. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  13010. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  13011. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  13012. }
  13013. // ALPHA HASH
  13014. if ( this.alphaHash === true ) {
  13015. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  13016. }
  13017. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  13018. diffuseColor.a.assign( 1.0 );
  13019. }
  13020. }
  13021. /**
  13022. * Abstract interface method that can be implemented by derived materials
  13023. * to setup material-specific node variables.
  13024. *
  13025. * @abstract
  13026. * @param {NodeBuilder} builder - The current node builder.
  13027. */
  13028. setupVariants( /*builder*/ ) {
  13029. // Interface function.
  13030. }
  13031. /**
  13032. * Setups the outgoing light node variable
  13033. *
  13034. * @return {Node<vec3>} The outgoing light node.
  13035. */
  13036. setupOutgoingLight() {
  13037. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  13038. }
  13039. /**
  13040. * Setups the normal node from the material.
  13041. *
  13042. * @return {Node<vec3>} The normal node.
  13043. */
  13044. setupNormal() {
  13045. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  13046. }
  13047. /**
  13048. * Setups the environment node from the material.
  13049. *
  13050. * @param {NodeBuilder} builder - The current node builder.
  13051. * @return {Node<vec4>} The environment node.
  13052. */
  13053. setupEnvironment( /*builder*/ ) {
  13054. let node = null;
  13055. if ( this.envNode ) {
  13056. node = this.envNode;
  13057. } else if ( this.envMap ) {
  13058. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  13059. }
  13060. return node;
  13061. }
  13062. /**
  13063. * Setups the light map node from the material.
  13064. *
  13065. * @param {NodeBuilder} builder - The current node builder.
  13066. * @return {Node<vec3>} The light map node.
  13067. */
  13068. setupLightMap( builder ) {
  13069. let node = null;
  13070. if ( builder.material.lightMap ) {
  13071. node = new IrradianceNode( materialLightMap );
  13072. }
  13073. return node;
  13074. }
  13075. /**
  13076. * Setups the lights node based on the scene, environment and material.
  13077. *
  13078. * @param {NodeBuilder} builder - The current node builder.
  13079. * @return {LightsNode} The lights node.
  13080. */
  13081. setupLights( builder ) {
  13082. const materialLightsNode = [];
  13083. //
  13084. const envNode = this.setupEnvironment( builder );
  13085. if ( envNode && envNode.isLightingNode ) {
  13086. materialLightsNode.push( envNode );
  13087. }
  13088. const lightMapNode = this.setupLightMap( builder );
  13089. if ( lightMapNode && lightMapNode.isLightingNode ) {
  13090. materialLightsNode.push( lightMapNode );
  13091. }
  13092. if ( this.aoNode !== null || builder.material.aoMap ) {
  13093. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  13094. materialLightsNode.push( new AONode( aoNode ) );
  13095. }
  13096. let lightsN = this.lightsNode || builder.lightsNode;
  13097. if ( materialLightsNode.length > 0 ) {
  13098. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  13099. }
  13100. return lightsN;
  13101. }
  13102. /**
  13103. * This method should be implemented by most derived materials
  13104. * since it defines the material's lighting model.
  13105. *
  13106. * @abstract
  13107. * @param {NodeBuilder} builder - The current node builder.
  13108. * @return {LightingModel} The lighting model.
  13109. */
  13110. setupLightingModel( /*builder*/ ) {
  13111. // Interface function.
  13112. }
  13113. /**
  13114. * Setups the outgoing light node.
  13115. *
  13116. * @param {NodeBuilder} builder - The current node builder.
  13117. * @return {Node<vec3>} The outgoing light node.
  13118. */
  13119. setupLighting( builder ) {
  13120. const { material } = builder;
  13121. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  13122. // OUTGOING LIGHT
  13123. const lights = this.lights === true || this.lightsNode !== null;
  13124. const lightsNode = lights ? this.setupLights( builder ) : null;
  13125. let outgoingLightNode = this.setupOutgoingLight( builder );
  13126. if ( lightsNode && lightsNode.getScope().hasLights ) {
  13127. const lightingModel = this.setupLightingModel( builder ) || null;
  13128. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  13129. } else if ( backdropNode !== null ) {
  13130. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  13131. }
  13132. // EMISSIVE
  13133. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  13134. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  13135. outgoingLightNode = outgoingLightNode.add( emissive );
  13136. }
  13137. return outgoingLightNode;
  13138. }
  13139. /**
  13140. * Setup the fog.
  13141. *
  13142. * @param {NodeBuilder} builder - The current node builder.
  13143. * @param {Node<vec4>} outputNode - The existing output node.
  13144. * @return {Node<vec4>} The output node.
  13145. */
  13146. setupFog( builder, outputNode ) {
  13147. const fogNode = builder.fogNode;
  13148. if ( fogNode ) {
  13149. output.assign( outputNode );
  13150. outputNode = vec4( fogNode );
  13151. }
  13152. return outputNode;
  13153. }
  13154. /**
  13155. * Setups the output node.
  13156. *
  13157. * @param {NodeBuilder} builder - The current node builder.
  13158. * @param {Node<vec4>} outputNode - The existing output node.
  13159. * @return {Node<vec4>} The output node.
  13160. */
  13161. setupOutput( builder, outputNode ) {
  13162. // FOG
  13163. if ( this.fog === true ) {
  13164. outputNode = this.setupFog( builder, outputNode );
  13165. }
  13166. return outputNode;
  13167. }
  13168. /**
  13169. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  13170. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  13171. * defining all material properties of the classic type in the node type.
  13172. *
  13173. * @param {Material} material - The material to copy properties with their values to this node material.
  13174. */
  13175. setDefaultValues( material ) {
  13176. // This approach is to reuse the native refreshUniforms*
  13177. // and turn available the use of features like transmission and environment in core
  13178. for ( const property in material ) {
  13179. const value = material[ property ];
  13180. if ( this[ property ] === undefined ) {
  13181. this[ property ] = value;
  13182. if ( value && value.clone ) this[ property ] = value.clone();
  13183. }
  13184. }
  13185. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  13186. for ( const key in descriptors ) {
  13187. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  13188. descriptors[ key ].get !== undefined ) {
  13189. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  13190. }
  13191. }
  13192. }
  13193. /**
  13194. * Serializes this material to JSON.
  13195. *
  13196. * @param {?(Object|string)} meta - The meta information for serialization.
  13197. * @return {Object} The serialized node.
  13198. */
  13199. toJSON( meta ) {
  13200. const isRoot = ( meta === undefined || typeof meta === 'string' );
  13201. if ( isRoot ) {
  13202. meta = {
  13203. textures: {},
  13204. images: {},
  13205. nodes: {}
  13206. };
  13207. }
  13208. const data = Material.prototype.toJSON.call( this, meta );
  13209. const nodeChildren = getNodeChildren( this );
  13210. data.inputNodes = {};
  13211. for ( const { property, childNode } of nodeChildren ) {
  13212. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  13213. }
  13214. // TODO: Copied from Object3D.toJSON
  13215. function extractFromCache( cache ) {
  13216. const values = [];
  13217. for ( const key in cache ) {
  13218. const data = cache[ key ];
  13219. delete data.metadata;
  13220. values.push( data );
  13221. }
  13222. return values;
  13223. }
  13224. if ( isRoot ) {
  13225. const textures = extractFromCache( meta.textures );
  13226. const images = extractFromCache( meta.images );
  13227. const nodes = extractFromCache( meta.nodes );
  13228. if ( textures.length > 0 ) data.textures = textures;
  13229. if ( images.length > 0 ) data.images = images;
  13230. if ( nodes.length > 0 ) data.nodes = nodes;
  13231. }
  13232. return data;
  13233. }
  13234. /**
  13235. * Copies the properties of the given node material to this instance.
  13236. *
  13237. * @param {NodeMaterial} source - The material to copy.
  13238. * @return {NodeMaterial} A reference to this node material.
  13239. */
  13240. copy( source ) {
  13241. this.lightsNode = source.lightsNode;
  13242. this.envNode = source.envNode;
  13243. this.colorNode = source.colorNode;
  13244. this.normalNode = source.normalNode;
  13245. this.opacityNode = source.opacityNode;
  13246. this.backdropNode = source.backdropNode;
  13247. this.backdropAlphaNode = source.backdropAlphaNode;
  13248. this.alphaTestNode = source.alphaTestNode;
  13249. this.positionNode = source.positionNode;
  13250. this.geometryNode = source.geometryNode;
  13251. this.depthNode = source.depthNode;
  13252. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  13253. this.castShadowPositionNode = source.castShadowPositionNode;
  13254. this.receivedShadowNode = source.receivedShadowNode;
  13255. this.castShadowNode = source.castShadowNode;
  13256. this.outputNode = source.outputNode;
  13257. this.mrtNode = source.mrtNode;
  13258. this.fragmentNode = source.fragmentNode;
  13259. this.vertexNode = source.vertexNode;
  13260. return super.copy( source );
  13261. }
  13262. }
  13263. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  13264. /**
  13265. * Node material version of {@link LineBasicMaterial}.
  13266. *
  13267. * @augments NodeMaterial
  13268. */
  13269. class LineBasicNodeMaterial extends NodeMaterial {
  13270. static get type() {
  13271. return 'LineBasicNodeMaterial';
  13272. }
  13273. /**
  13274. * Constructs a new line basic node material.
  13275. *
  13276. * @param {Object} [parameters] - The configuration parameter.
  13277. */
  13278. constructor( parameters ) {
  13279. super();
  13280. /**
  13281. * This flag can be used for type testing.
  13282. *
  13283. * @type {boolean}
  13284. * @readonly
  13285. * @default true
  13286. */
  13287. this.isLineBasicNodeMaterial = true;
  13288. this.setDefaultValues( _defaultValues$d );
  13289. this.setValues( parameters );
  13290. }
  13291. }
  13292. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  13293. /**
  13294. * Node material version of {@link LineDashedMaterial}.
  13295. *
  13296. * @augments NodeMaterial
  13297. */
  13298. class LineDashedNodeMaterial extends NodeMaterial {
  13299. static get type() {
  13300. return 'LineDashedNodeMaterial';
  13301. }
  13302. /**
  13303. * Constructs a new line dashed node material.
  13304. *
  13305. * @param {Object} [parameters] - The configuration parameter.
  13306. */
  13307. constructor( parameters ) {
  13308. super();
  13309. /**
  13310. * This flag can be used for type testing.
  13311. *
  13312. * @type {boolean}
  13313. * @readonly
  13314. * @default true
  13315. */
  13316. this.isLineDashedNodeMaterial = true;
  13317. this.setDefaultValues( _defaultValues$c );
  13318. /**
  13319. * The dash offset.
  13320. *
  13321. * @type {number}
  13322. * @default 0
  13323. */
  13324. this.dashOffset = 0;
  13325. /**
  13326. * The offset of dash materials is by default inferred from the `dashOffset`
  13327. * property. This node property allows to overwrite the default
  13328. * and define the offset with a node instead.
  13329. *
  13330. * If you don't want to overwrite the offset but modify the existing
  13331. * value instead, use {@link materialLineDashOffset}.
  13332. *
  13333. * @type {?Node<float>}
  13334. * @default null
  13335. */
  13336. this.offsetNode = null;
  13337. /**
  13338. * The scale of dash materials is by default inferred from the `scale`
  13339. * property. This node property allows to overwrite the default
  13340. * and define the scale with a node instead.
  13341. *
  13342. * If you don't want to overwrite the scale but modify the existing
  13343. * value instead, use {@link materialLineScale}.
  13344. *
  13345. * @type {?Node<float>}
  13346. * @default null
  13347. */
  13348. this.dashScaleNode = null;
  13349. /**
  13350. * The dash size of dash materials is by default inferred from the `dashSize`
  13351. * property. This node property allows to overwrite the default
  13352. * and define the dash size with a node instead.
  13353. *
  13354. * If you don't want to overwrite the dash size but modify the existing
  13355. * value instead, use {@link materialLineDashSize}.
  13356. *
  13357. * @type {?Node<float>}
  13358. * @default null
  13359. */
  13360. this.dashSizeNode = null;
  13361. /**
  13362. * The gap size of dash materials is by default inferred from the `gapSize`
  13363. * property. This node property allows to overwrite the default
  13364. * and define the gap size with a node instead.
  13365. *
  13366. * If you don't want to overwrite the gap size but modify the existing
  13367. * value instead, use {@link materialLineGapSize}.
  13368. *
  13369. * @type {?Node<float>}
  13370. * @default null
  13371. */
  13372. this.gapSizeNode = null;
  13373. this.setValues( parameters );
  13374. }
  13375. /**
  13376. * Setups the dash specific node variables.
  13377. *
  13378. * @param {NodeBuilder} builder - The current node builder.
  13379. */
  13380. setupVariants( /* builder */ ) {
  13381. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13382. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13383. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13384. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13385. dashSize.assign( dashSizeNode );
  13386. gapSize.assign( gapSizeNode );
  13387. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  13388. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  13389. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  13390. }
  13391. }
  13392. let _sharedFramebuffer = null;
  13393. /**
  13394. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  13395. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  13396. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  13397. *
  13398. * @augments ViewportTextureNode
  13399. */
  13400. class ViewportSharedTextureNode extends ViewportTextureNode {
  13401. static get type() {
  13402. return 'ViewportSharedTextureNode';
  13403. }
  13404. /**
  13405. * Constructs a new viewport shared texture node.
  13406. *
  13407. * @param {Node} [uvNode=screenUV] - The uv node.
  13408. * @param {?Node} [levelNode=null] - The level node.
  13409. */
  13410. constructor( uvNode = screenUV, levelNode = null ) {
  13411. if ( _sharedFramebuffer === null ) {
  13412. _sharedFramebuffer = new FramebufferTexture();
  13413. }
  13414. super( uvNode, levelNode, _sharedFramebuffer );
  13415. }
  13416. updateReference() {
  13417. return this;
  13418. }
  13419. }
  13420. /**
  13421. * TSL function for creating a shared viewport texture node.
  13422. *
  13423. * @tsl
  13424. * @function
  13425. * @param {?Node} [uvNode=screenUV] - The uv node.
  13426. * @param {?Node} [levelNode=null] - The level node.
  13427. * @returns {ViewportSharedTextureNode}
  13428. */
  13429. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  13430. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  13431. /**
  13432. * This node material can be used to render lines with a size larger than one
  13433. * by representing them as instanced meshes.
  13434. *
  13435. * @augments NodeMaterial
  13436. */
  13437. class Line2NodeMaterial extends NodeMaterial {
  13438. static get type() {
  13439. return 'Line2NodeMaterial';
  13440. }
  13441. /**
  13442. * Constructs a new node material for wide line rendering.
  13443. *
  13444. * @param {Object} [parameters={}] - The configuration parameter.
  13445. */
  13446. constructor( parameters = {} ) {
  13447. super();
  13448. /**
  13449. * This flag can be used for type testing.
  13450. *
  13451. * @type {boolean}
  13452. * @readonly
  13453. * @default true
  13454. */
  13455. this.isLine2NodeMaterial = true;
  13456. this.setDefaultValues( _defaultValues$b );
  13457. /**
  13458. * Whether vertex colors should be used or not.
  13459. *
  13460. * @type {boolean}
  13461. * @default false
  13462. */
  13463. this.useColor = parameters.vertexColors;
  13464. /**
  13465. * The dash offset.
  13466. *
  13467. * @type {number}
  13468. * @default 0
  13469. */
  13470. this.dashOffset = 0;
  13471. /**
  13472. * The line width.
  13473. *
  13474. * @type {number}
  13475. * @default 0
  13476. */
  13477. this.lineWidth = 1;
  13478. /**
  13479. * Defines the lines color.
  13480. *
  13481. * @type {?Node<vec3>}
  13482. * @default null
  13483. */
  13484. this.lineColorNode = null;
  13485. /**
  13486. * Defines the offset.
  13487. *
  13488. * @type {?Node<float>}
  13489. * @default null
  13490. */
  13491. this.offsetNode = null;
  13492. /**
  13493. * Defines the dash scale.
  13494. *
  13495. * @type {?Node<float>}
  13496. * @default null
  13497. */
  13498. this.dashScaleNode = null;
  13499. /**
  13500. * Defines the dash size.
  13501. *
  13502. * @type {?Node<float>}
  13503. * @default null
  13504. */
  13505. this.dashSizeNode = null;
  13506. /**
  13507. * Defines the gap size.
  13508. *
  13509. * @type {?Node<float>}
  13510. * @default null
  13511. */
  13512. this.gapSizeNode = null;
  13513. /**
  13514. * Blending is set to `NoBlending` since transparency
  13515. * is not supported, yet.
  13516. *
  13517. * @type {number}
  13518. * @default 0
  13519. */
  13520. this.blending = NoBlending;
  13521. this._useDash = parameters.dashed;
  13522. this._useAlphaToCoverage = true;
  13523. this._useWorldUnits = false;
  13524. this.setValues( parameters );
  13525. }
  13526. /**
  13527. * Setups the vertex and fragment stage of this node material.
  13528. *
  13529. * @param {NodeBuilder} builder - The current node builder.
  13530. */
  13531. setup( builder ) {
  13532. const { renderer } = builder;
  13533. const useAlphaToCoverage = this._useAlphaToCoverage;
  13534. const useColor = this.useColor;
  13535. const useDash = this._useDash;
  13536. const useWorldUnits = this._useWorldUnits;
  13537. const trimSegment = Fn( ( { start, end } ) => {
  13538. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  13539. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  13540. const nearEstimate = b.mul( -0.5 ).div( a );
  13541. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  13542. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  13543. } ).setLayout( {
  13544. name: 'trimSegment',
  13545. type: 'vec4',
  13546. inputs: [
  13547. { name: 'start', type: 'vec4' },
  13548. { name: 'end', type: 'vec4' }
  13549. ]
  13550. } );
  13551. this.vertexNode = Fn( () => {
  13552. const instanceStart = attribute( 'instanceStart' );
  13553. const instanceEnd = attribute( 'instanceEnd' );
  13554. // camera space
  13555. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  13556. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  13557. if ( useDash ) {
  13558. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13559. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13560. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  13561. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  13562. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  13563. lineDistance = lineDistance.add( offsetNode );
  13564. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  13565. }
  13566. if ( useWorldUnits ) {
  13567. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  13568. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  13569. }
  13570. const aspect = viewport.z.div( viewport.w );
  13571. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  13572. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  13573. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  13574. // perhaps there is a more elegant solution -- WestLangley
  13575. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  13576. If( perspective, () => {
  13577. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  13578. end.assign( trimSegment( { start: start, end: end } ) );
  13579. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  13580. start.assign( trimSegment( { start: end, end: start } ) );
  13581. } );
  13582. } );
  13583. // clip space
  13584. const clipStart = cameraProjectionMatrix.mul( start );
  13585. const clipEnd = cameraProjectionMatrix.mul( end );
  13586. // ndc space
  13587. const ndcStart = clipStart.xyz.div( clipStart.w );
  13588. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  13589. // direction
  13590. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  13591. // account for clip-space aspect ratio
  13592. dir.x.assign( dir.x.mul( aspect ) );
  13593. dir.assign( dir.normalize() );
  13594. const clip = vec4().toVar();
  13595. if ( useWorldUnits ) {
  13596. // get the offset direction as perpendicular to the view vector
  13597. const worldDir = end.xyz.sub( start.xyz ).normalize();
  13598. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  13599. const worldUp = worldDir.cross( tmpFwd ).normalize();
  13600. const worldFwd = worldDir.cross( worldUp );
  13601. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  13602. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  13603. // height offset
  13604. const hw = materialLineWidth.mul( 0.5 );
  13605. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  13606. // don't extend the line if we're rendering dashes because we
  13607. // won't be rendering the endcaps
  13608. if ( ! useDash ) {
  13609. // cap extension
  13610. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  13611. // add width to the box
  13612. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  13613. // endcaps
  13614. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  13615. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  13616. } );
  13617. }
  13618. // project the worldpos
  13619. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  13620. // shift the depth of the projected points so the line
  13621. // segments overlap neatly
  13622. const clipPose = vec3().toVar();
  13623. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  13624. clip.z.assign( clipPose.z.mul( clip.w ) );
  13625. } else {
  13626. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  13627. // undo aspect ratio adjustment
  13628. dir.x.assign( dir.x.div( aspect ) );
  13629. offset.x.assign( offset.x.div( aspect ) );
  13630. // sign flip
  13631. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  13632. // endcaps
  13633. If( positionGeometry.y.lessThan( 0.0 ), () => {
  13634. offset.assign( offset.sub( dir ) );
  13635. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  13636. offset.assign( offset.add( dir ) );
  13637. } );
  13638. // adjust for linewidth
  13639. offset.assign( offset.mul( materialLineWidth ) );
  13640. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  13641. offset.assign( offset.div( viewport.w ) );
  13642. // select end
  13643. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  13644. // back to clip space
  13645. offset.assign( offset.mul( clip.w ) );
  13646. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  13647. }
  13648. return clip;
  13649. } )();
  13650. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  13651. const p13 = p1.sub( p3 );
  13652. const p43 = p4.sub( p3 );
  13653. const p21 = p2.sub( p1 );
  13654. const d1343 = p13.dot( p43 );
  13655. const d4321 = p43.dot( p21 );
  13656. const d1321 = p13.dot( p21 );
  13657. const d4343 = p43.dot( p43 );
  13658. const d2121 = p21.dot( p21 );
  13659. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  13660. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  13661. const mua = numer.div( denom ).clamp();
  13662. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  13663. return vec2( mua, mub );
  13664. } );
  13665. this.colorNode = Fn( () => {
  13666. const vUv = uv();
  13667. if ( useDash ) {
  13668. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13669. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13670. dashSize.assign( dashSizeNode );
  13671. gapSize.assign( gapSizeNode );
  13672. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  13673. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  13674. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  13675. }
  13676. const alpha = float( 1 ).toVar( 'alpha' );
  13677. if ( useWorldUnits ) {
  13678. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  13679. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  13680. // Find the closest points on the view ray and the line segment
  13681. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  13682. const lineDir = worldEnd.sub( worldStart );
  13683. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  13684. const p1 = worldStart.add( lineDir.mul( params.x ) );
  13685. const p2 = rayEnd.mul( params.y );
  13686. const delta = p1.sub( p2 );
  13687. const len = delta.length();
  13688. const norm = len.div( materialLineWidth );
  13689. if ( ! useDash ) {
  13690. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  13691. const dnorm = norm.fwidth();
  13692. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  13693. } else {
  13694. norm.greaterThan( 0.5 ).discard();
  13695. }
  13696. }
  13697. } else {
  13698. // round endcaps
  13699. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  13700. const a = vUv.x;
  13701. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  13702. const len2 = a.mul( a ).add( b.mul( b ) );
  13703. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  13704. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  13705. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  13706. } );
  13707. } else {
  13708. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  13709. const a = vUv.x;
  13710. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  13711. const len2 = a.mul( a ).add( b.mul( b ) );
  13712. len2.greaterThan( 1.0 ).discard();
  13713. } );
  13714. }
  13715. }
  13716. let lineColorNode;
  13717. if ( this.lineColorNode ) {
  13718. lineColorNode = this.lineColorNode;
  13719. } else {
  13720. if ( useColor ) {
  13721. const instanceColorStart = attribute( 'instanceColorStart' );
  13722. const instanceColorEnd = attribute( 'instanceColorEnd' );
  13723. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  13724. lineColorNode = instanceColor.mul( materialColor );
  13725. } else {
  13726. lineColorNode = materialColor;
  13727. }
  13728. }
  13729. return vec4( lineColorNode, alpha );
  13730. } )();
  13731. if ( this.transparent ) {
  13732. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13733. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  13734. }
  13735. super.setup( builder );
  13736. }
  13737. /**
  13738. * Whether the lines should sized in world units or not.
  13739. * When set to `false` the unit is pixel.
  13740. *
  13741. * @type {boolean}
  13742. * @default false
  13743. */
  13744. get worldUnits() {
  13745. return this._useWorldUnits;
  13746. }
  13747. set worldUnits( value ) {
  13748. if ( this._useWorldUnits !== value ) {
  13749. this._useWorldUnits = value;
  13750. this.needsUpdate = true;
  13751. }
  13752. }
  13753. /**
  13754. * Whether the lines should be dashed or not.
  13755. *
  13756. * @type {boolean}
  13757. * @default false
  13758. */
  13759. get dashed() {
  13760. return this._useDash;
  13761. }
  13762. set dashed( value ) {
  13763. if ( this._useDash !== value ) {
  13764. this._useDash = value;
  13765. this.needsUpdate = true;
  13766. }
  13767. }
  13768. /**
  13769. * Whether alpha to coverage should be used or not.
  13770. *
  13771. * @type {boolean}
  13772. * @default true
  13773. */
  13774. get alphaToCoverage() {
  13775. return this._useAlphaToCoverage;
  13776. }
  13777. set alphaToCoverage( value ) {
  13778. if ( this._useAlphaToCoverage !== value ) {
  13779. this._useAlphaToCoverage = value;
  13780. this.needsUpdate = true;
  13781. }
  13782. }
  13783. }
  13784. /**
  13785. * Packs a direction vector into a color value.
  13786. *
  13787. * @tsl
  13788. * @function
  13789. * @param {Node<vec3>} node - The direction to pack.
  13790. * @return {Node<vec3>} The color.
  13791. */
  13792. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  13793. /**
  13794. * Unpacks a color value into a direction vector.
  13795. *
  13796. * @tsl
  13797. * @function
  13798. * @param {Node<vec3>} node - The color to unpack.
  13799. * @return {Node<vec3>} The direction.
  13800. */
  13801. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  13802. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  13803. /**
  13804. * Node material version of {@link MeshNormalMaterial}.
  13805. *
  13806. * @augments NodeMaterial
  13807. */
  13808. class MeshNormalNodeMaterial extends NodeMaterial {
  13809. static get type() {
  13810. return 'MeshNormalNodeMaterial';
  13811. }
  13812. /**
  13813. * Constructs a new mesh normal node material.
  13814. *
  13815. * @param {Object} [parameters] - The configuration parameter.
  13816. */
  13817. constructor( parameters ) {
  13818. super();
  13819. /**
  13820. * This flag can be used for type testing.
  13821. *
  13822. * @type {boolean}
  13823. * @readonly
  13824. * @default true
  13825. */
  13826. this.isMeshNormalNodeMaterial = true;
  13827. this.setDefaultValues( _defaultValues$a );
  13828. this.setValues( parameters );
  13829. }
  13830. /**
  13831. * Overwrites the default implementation by computing the diffuse color
  13832. * based on the normal data.
  13833. */
  13834. setupDiffuseColor() {
  13835. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13836. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  13837. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( transformedNormalView ), opacityNode ), SRGBColorSpace ) );
  13838. }
  13839. }
  13840. /**
  13841. * Can be used to compute texture coordinates for projecting an
  13842. * equirectangular texture onto a mesh for using it as the scene's
  13843. * background.
  13844. *
  13845. * ```js
  13846. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  13847. * ```
  13848. *
  13849. * @augments TempNode
  13850. */
  13851. class EquirectUVNode extends TempNode {
  13852. static get type() {
  13853. return 'EquirectUVNode';
  13854. }
  13855. /**
  13856. * Constructs a new equirect uv node.
  13857. *
  13858. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  13859. */
  13860. constructor( dirNode = positionWorldDirection ) {
  13861. super( 'vec2' );
  13862. /**
  13863. * A direction vector for sampling why is by default `positionWorldDirection`.
  13864. *
  13865. * @type {Node<vec3>}
  13866. */
  13867. this.dirNode = dirNode;
  13868. }
  13869. setup() {
  13870. const dir = this.dirNode;
  13871. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  13872. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  13873. return vec2( u, v );
  13874. }
  13875. }
  13876. /**
  13877. * TSL function for creating an equirect uv node.
  13878. *
  13879. * @tsl
  13880. * @function
  13881. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  13882. * @returns {EquirectUVNode}
  13883. */
  13884. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode ).setParameterLength( 0, 1 );
  13885. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  13886. /**
  13887. * This class represents a cube render target. It is a special version
  13888. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  13889. *
  13890. * @augments WebGLCubeRenderTarget
  13891. */
  13892. class CubeRenderTarget extends WebGLCubeRenderTarget {
  13893. /**
  13894. * Constructs a new cube render target.
  13895. *
  13896. * @param {number} [size=1] - The size of the render target.
  13897. * @param {RenderTarget~Options} [options] - The configuration object.
  13898. */
  13899. constructor( size = 1, options = {} ) {
  13900. super( size, options );
  13901. /**
  13902. * This flag can be used for type testing.
  13903. *
  13904. * @type {boolean}
  13905. * @readonly
  13906. * @default true
  13907. */
  13908. this.isCubeRenderTarget = true;
  13909. }
  13910. /**
  13911. * Converts the given equirectangular texture to a cube map.
  13912. *
  13913. * @param {Renderer} renderer - The renderer.
  13914. * @param {Texture} texture - The equirectangular texture.
  13915. * @return {CubeRenderTarget} A reference to this cube render target.
  13916. */
  13917. fromEquirectangularTexture( renderer, texture$1 ) {
  13918. const currentMinFilter = texture$1.minFilter;
  13919. const currentGenerateMipmaps = texture$1.generateMipmaps;
  13920. texture$1.generateMipmaps = true;
  13921. this.texture.type = texture$1.type;
  13922. this.texture.colorSpace = texture$1.colorSpace;
  13923. this.texture.generateMipmaps = texture$1.generateMipmaps;
  13924. this.texture.minFilter = texture$1.minFilter;
  13925. this.texture.magFilter = texture$1.magFilter;
  13926. const geometry = new BoxGeometry( 5, 5, 5 );
  13927. const uvNode = equirectUV( positionWorldDirection );
  13928. const material = new NodeMaterial();
  13929. material.colorNode = texture( texture$1, uvNode, 0 );
  13930. material.side = BackSide;
  13931. material.blending = NoBlending;
  13932. const mesh = new Mesh( geometry, material );
  13933. const scene = new Scene();
  13934. scene.add( mesh );
  13935. // Avoid blurred poles
  13936. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  13937. const camera = new CubeCamera( 1, 10, this );
  13938. const currentMRT = renderer.getMRT();
  13939. renderer.setMRT( null );
  13940. camera.update( renderer, scene );
  13941. renderer.setMRT( currentMRT );
  13942. texture$1.minFilter = currentMinFilter;
  13943. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  13944. mesh.geometry.dispose();
  13945. mesh.material.dispose();
  13946. return this;
  13947. }
  13948. }
  13949. const _cache$1 = new WeakMap();
  13950. /**
  13951. * This node can be used to automatically convert environment maps in the
  13952. * equirectangular format into the cube map format.
  13953. *
  13954. * @augments TempNode
  13955. */
  13956. class CubeMapNode extends TempNode {
  13957. static get type() {
  13958. return 'CubeMapNode';
  13959. }
  13960. /**
  13961. * Constructs a new cube map node.
  13962. *
  13963. * @param {Node} envNode - The node representing the environment map.
  13964. */
  13965. constructor( envNode ) {
  13966. super( 'vec3' );
  13967. /**
  13968. * The node representing the environment map.
  13969. *
  13970. * @type {Node}
  13971. */
  13972. this.envNode = envNode;
  13973. /**
  13974. * A reference to the internal cube texture.
  13975. *
  13976. * @private
  13977. * @type {?CubeTexture}
  13978. * @default null
  13979. */
  13980. this._cubeTexture = null;
  13981. /**
  13982. * A reference to the internal cube texture node.
  13983. *
  13984. * @private
  13985. * @type {CubeTextureNode}
  13986. */
  13987. this._cubeTextureNode = cubeTexture( null );
  13988. const defaultTexture = new CubeTexture();
  13989. defaultTexture.isRenderTargetTexture = true;
  13990. /**
  13991. * A default cube texture that acts as a placeholder.
  13992. * It is used when the conversion from equirectangular to cube
  13993. * map has not finished yet for a given texture.
  13994. *
  13995. * @private
  13996. * @type {CubeTexture}
  13997. */
  13998. this._defaultTexture = defaultTexture;
  13999. /**
  14000. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14001. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14002. *
  14003. * @type {string}
  14004. * @default 'render'
  14005. */
  14006. this.updateBeforeType = NodeUpdateType.RENDER;
  14007. }
  14008. updateBefore( frame ) {
  14009. const { renderer, material } = frame;
  14010. const envNode = this.envNode;
  14011. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14012. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14013. if ( texture && texture.isTexture ) {
  14014. const mapping = texture.mapping;
  14015. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  14016. // check for converted cubemap map
  14017. if ( _cache$1.has( texture ) ) {
  14018. const cubeMap = _cache$1.get( texture );
  14019. mapTextureMapping( cubeMap, texture.mapping );
  14020. this._cubeTexture = cubeMap;
  14021. } else {
  14022. // create cube map from equirectangular map
  14023. const image = texture.image;
  14024. if ( isEquirectangularMapReady$1( image ) ) {
  14025. const renderTarget = new CubeRenderTarget( image.height );
  14026. renderTarget.fromEquirectangularTexture( renderer, texture );
  14027. mapTextureMapping( renderTarget.texture, texture.mapping );
  14028. this._cubeTexture = renderTarget.texture;
  14029. _cache$1.set( texture, renderTarget.texture );
  14030. texture.addEventListener( 'dispose', onTextureDispose );
  14031. } else {
  14032. // default cube texture as fallback when equirectangular texture is not yet loaded
  14033. this._cubeTexture = this._defaultTexture;
  14034. }
  14035. }
  14036. //
  14037. this._cubeTextureNode.value = this._cubeTexture;
  14038. } else {
  14039. // envNode already refers to a cube map
  14040. this._cubeTextureNode = this.envNode;
  14041. }
  14042. }
  14043. }
  14044. }
  14045. setup( builder ) {
  14046. this.updateBefore( builder );
  14047. return this._cubeTextureNode;
  14048. }
  14049. }
  14050. /**
  14051. * Returns true if the given equirectangular image has been fully loaded
  14052. * and is ready for further processing.
  14053. *
  14054. * @private
  14055. * @param {Image} image - The equirectangular image to check.
  14056. * @return {boolean} Whether the image is ready or not.
  14057. */
  14058. function isEquirectangularMapReady$1( image ) {
  14059. if ( image === null || image === undefined ) return false;
  14060. return image.height > 0;
  14061. }
  14062. /**
  14063. * This function is executed when `dispose()` is called on the equirectangular
  14064. * texture. In this case, the generated cube map with its render target
  14065. * is deleted as well.
  14066. *
  14067. * @private
  14068. * @param {Object} event - The event object.
  14069. */
  14070. function onTextureDispose( event ) {
  14071. const texture = event.target;
  14072. texture.removeEventListener( 'dispose', onTextureDispose );
  14073. const renderTarget = _cache$1.get( texture );
  14074. if ( renderTarget !== undefined ) {
  14075. _cache$1.delete( texture );
  14076. renderTarget.dispose();
  14077. }
  14078. }
  14079. /**
  14080. * This function makes sure the generated cube map uses the correct
  14081. * texture mapping that corresponds to the equirectangular original.
  14082. *
  14083. * @private
  14084. * @param {Texture} texture - The cube texture.
  14085. * @param {number} mapping - The original texture mapping.
  14086. */
  14087. function mapTextureMapping( texture, mapping ) {
  14088. if ( mapping === EquirectangularReflectionMapping ) {
  14089. texture.mapping = CubeReflectionMapping;
  14090. } else if ( mapping === EquirectangularRefractionMapping ) {
  14091. texture.mapping = CubeRefractionMapping;
  14092. }
  14093. }
  14094. /**
  14095. * TSL function for creating a cube map node.
  14096. *
  14097. * @tsl
  14098. * @function
  14099. * @param {Node} envNode - The node representing the environment map.
  14100. * @returns {CubeMapNode}
  14101. */
  14102. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  14103. /**
  14104. * Represents a basic model for Image-based lighting (IBL). The environment
  14105. * is defined via environment maps in the equirectangular or cube map format.
  14106. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  14107. * or {@link MeshPhongNodeMaterial}.
  14108. *
  14109. * @augments LightingNode
  14110. */
  14111. class BasicEnvironmentNode extends LightingNode {
  14112. static get type() {
  14113. return 'BasicEnvironmentNode';
  14114. }
  14115. /**
  14116. * Constructs a new basic environment node.
  14117. *
  14118. * @param {Node} [envNode=null] - A node representing the environment.
  14119. */
  14120. constructor( envNode = null ) {
  14121. super();
  14122. /**
  14123. * A node representing the environment.
  14124. *
  14125. * @type {Node}
  14126. * @default null
  14127. */
  14128. this.envNode = envNode;
  14129. }
  14130. setup( builder ) {
  14131. // environment property is used in the finish() method of BasicLightingModel
  14132. builder.context.environment = cubeMapNode( this.envNode );
  14133. }
  14134. }
  14135. /**
  14136. * A specific version of {@link IrradianceNode} that is only relevant
  14137. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  14138. * requires a special scaling factor for the light map.
  14139. *
  14140. * @augments LightingNode
  14141. */
  14142. class BasicLightMapNode extends LightingNode {
  14143. static get type() {
  14144. return 'BasicLightMapNode';
  14145. }
  14146. /**
  14147. * Constructs a new basic light map node.
  14148. *
  14149. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  14150. */
  14151. constructor( lightMapNode = null ) {
  14152. super();
  14153. /**
  14154. * The light map node.
  14155. *
  14156. * @type {?Node<vec3>}
  14157. */
  14158. this.lightMapNode = lightMapNode;
  14159. }
  14160. setup( builder ) {
  14161. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  14162. const RECIPROCAL_PI = float( 1 / Math.PI );
  14163. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  14164. }
  14165. }
  14166. /**
  14167. * Abstract class for implementing lighting models. The module defines
  14168. * multiple methods that concrete lighting models can implement. These
  14169. * methods are executed at different points during the light evaluation
  14170. * process.
  14171. */
  14172. class LightingModel {
  14173. /**
  14174. * This method is intended for setting up lighting model and context data
  14175. * which are later used in the evaluation process.
  14176. *
  14177. * @abstract
  14178. * @param {NodeBuilder} builder - The current node builder.
  14179. */
  14180. start( builder ) {
  14181. // lights ( direct )
  14182. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  14183. // indirect
  14184. this.indirect( builder );
  14185. }
  14186. /**
  14187. * This method is intended for executing final tasks like final updates
  14188. * to the outgoing light.
  14189. *
  14190. * @abstract
  14191. * @param {NodeBuilder} builder - The current node builder.
  14192. */
  14193. finish( /*builder*/ ) { }
  14194. /**
  14195. * This method is intended for implementing the direct light term and
  14196. * executed during the build process of directional, point and spot light nodes.
  14197. *
  14198. * @abstract
  14199. * @param {Object} lightData - The light data.
  14200. * @param {NodeBuilder} builder - The current node builder.
  14201. */
  14202. direct( /*lightData, builder*/ ) { }
  14203. /**
  14204. * This method is intended for implementing the direct light term for
  14205. * rect area light nodes.
  14206. *
  14207. * @abstract
  14208. * @param {Object} lightData - The light data.
  14209. * @param {NodeBuilder} builder - The current node builder.
  14210. */
  14211. directRectArea( /*lightData, builder*/ ) {}
  14212. /**
  14213. * This method is intended for implementing the indirect light term.
  14214. *
  14215. * @abstract
  14216. * @param {NodeBuilder} builder - The current node builder.
  14217. */
  14218. indirect( /*builder*/ ) { }
  14219. /**
  14220. * This method is intended for implementing the ambient occlusion term.
  14221. * Unlike other methods, this method must be called manually by the lighting
  14222. * model in its indirect term.
  14223. *
  14224. * @abstract
  14225. * @param {NodeBuilder} builder - The current node builder.
  14226. */
  14227. ambientOcclusion( /*input, stack, builder*/ ) { }
  14228. }
  14229. /**
  14230. * Represents the lighting model for unlit materials. The only light contribution
  14231. * is baked indirect lighting modulated with ambient occlusion and the material's
  14232. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  14233. *
  14234. * @augments LightingModel
  14235. */
  14236. class BasicLightingModel extends LightingModel {
  14237. /**
  14238. * Constructs a new basic lighting model.
  14239. */
  14240. constructor() {
  14241. super();
  14242. }
  14243. /**
  14244. * Implements the baked indirect lighting with its modulation.
  14245. *
  14246. * @param {NodeBuilder} builder - The current node builder.
  14247. */
  14248. indirect( { context } ) {
  14249. const ambientOcclusion = context.ambientOcclusion;
  14250. const reflectedLight = context.reflectedLight;
  14251. const irradianceLightMap = context.irradianceLightMap;
  14252. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  14253. // accumulation (baked indirect lighting only)
  14254. if ( irradianceLightMap ) {
  14255. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  14256. } else {
  14257. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  14258. }
  14259. // modulation
  14260. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14261. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  14262. }
  14263. /**
  14264. * Implements the environment mapping.
  14265. *
  14266. * @param {NodeBuilder} builder - The current node builder.
  14267. */
  14268. finish( builder ) {
  14269. const { material, context } = builder;
  14270. const outgoingLight = context.outgoingLight;
  14271. const envNode = builder.context.environment;
  14272. if ( envNode ) {
  14273. switch ( material.combine ) {
  14274. case MultiplyOperation:
  14275. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  14276. break;
  14277. case MixOperation:
  14278. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  14279. break;
  14280. case AddOperation:
  14281. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  14282. break;
  14283. default:
  14284. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  14285. break;
  14286. }
  14287. }
  14288. }
  14289. }
  14290. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  14291. /**
  14292. * Node material version of {@link MeshBasicMaterial}.
  14293. *
  14294. * @augments NodeMaterial
  14295. */
  14296. class MeshBasicNodeMaterial extends NodeMaterial {
  14297. static get type() {
  14298. return 'MeshBasicNodeMaterial';
  14299. }
  14300. /**
  14301. * Constructs a new mesh basic node material.
  14302. *
  14303. * @param {Object} [parameters] - The configuration parameter.
  14304. */
  14305. constructor( parameters ) {
  14306. super();
  14307. /**
  14308. * This flag can be used for type testing.
  14309. *
  14310. * @type {boolean}
  14311. * @readonly
  14312. * @default true
  14313. */
  14314. this.isMeshBasicNodeMaterial = true;
  14315. /**
  14316. * Although the basic material is by definition unlit, we set
  14317. * this property to `true` since we use a lighting model to compute
  14318. * the outgoing light of the fragment shader.
  14319. *
  14320. * @type {boolean}
  14321. * @default true
  14322. */
  14323. this.lights = true;
  14324. this.setDefaultValues( _defaultValues$9 );
  14325. this.setValues( parameters );
  14326. }
  14327. /**
  14328. * Basic materials are not affected by normal and bump maps so we
  14329. * return by default {@link normalView}.
  14330. *
  14331. * @return {Node<vec3>} The normal node.
  14332. */
  14333. setupNormal() {
  14334. return normalView; // see #28839
  14335. }
  14336. /**
  14337. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14338. * to implement the default environment mapping.
  14339. *
  14340. * @param {NodeBuilder} builder - The current node builder.
  14341. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14342. */
  14343. setupEnvironment( builder ) {
  14344. const envNode = super.setupEnvironment( builder );
  14345. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14346. }
  14347. /**
  14348. * This method must be overwritten since light maps are evaluated
  14349. * with a special scaling factor for basic materials.
  14350. *
  14351. * @param {NodeBuilder} builder - The current node builder.
  14352. * @return {?BasicLightMapNode<vec3>} The light map node.
  14353. */
  14354. setupLightMap( builder ) {
  14355. let node = null;
  14356. if ( builder.material.lightMap ) {
  14357. node = new BasicLightMapNode( materialLightMap );
  14358. }
  14359. return node;
  14360. }
  14361. /**
  14362. * The material overwrites this method because `lights` is set to `true` but
  14363. * we still want to return the diffuse color as the outgoing light.
  14364. *
  14365. * @return {Node<vec3>} The outgoing light node.
  14366. */
  14367. setupOutgoingLight() {
  14368. return diffuseColor.rgb;
  14369. }
  14370. /**
  14371. * Setups the lighting model.
  14372. *
  14373. * @return {BasicLightingModel} The lighting model.
  14374. */
  14375. setupLightingModel() {
  14376. return new BasicLightingModel();
  14377. }
  14378. }
  14379. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  14380. // Original approximation by Christophe Schlick '94
  14381. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  14382. // Optimized variant (presented by Epic at SIGGRAPH '13)
  14383. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  14384. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  14385. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  14386. } ); // validated
  14387. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  14388. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  14389. } ); // validated
  14390. const G_BlinnPhong_Implicit = () => float( 0.25 );
  14391. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  14392. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  14393. } );
  14394. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14395. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14396. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14397. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14398. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  14399. const G = G_BlinnPhong_Implicit();
  14400. const D = D_BlinnPhong( { dotNH } );
  14401. return F.mul( G ).mul( D );
  14402. } );
  14403. /**
  14404. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  14405. *
  14406. * @augments BasicLightingModel
  14407. */
  14408. class PhongLightingModel extends BasicLightingModel {
  14409. /**
  14410. * Constructs a new phong lighting model.
  14411. *
  14412. * @param {boolean} [specular=true] - Whether specular is supported or not.
  14413. */
  14414. constructor( specular = true ) {
  14415. super();
  14416. /**
  14417. * Whether specular is supported or not. Set this to `false` if you are
  14418. * looking for a Lambert-like material meaning a material for non-shiny
  14419. * surfaces, without specular highlights.
  14420. *
  14421. * @type {boolean}
  14422. * @default true
  14423. */
  14424. this.specular = specular;
  14425. }
  14426. /**
  14427. * Implements the direct lighting. The specular portion is optional an can be controlled
  14428. * with the {@link PhongLightingModel#specular} flag.
  14429. *
  14430. * @param {Object} lightData - The light data.
  14431. */
  14432. direct( { lightDirection, lightColor, reflectedLight } ) {
  14433. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14434. const irradiance = dotNL.mul( lightColor );
  14435. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14436. if ( this.specular === true ) {
  14437. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  14438. }
  14439. }
  14440. /**
  14441. * Implements the indirect lighting.
  14442. *
  14443. * @param {NodeBuilder} builder - The current node builder.
  14444. */
  14445. indirect( builder ) {
  14446. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  14447. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14448. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14449. }
  14450. }
  14451. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  14452. /**
  14453. * Node material version of {@link MeshLambertMaterial}.
  14454. *
  14455. * @augments NodeMaterial
  14456. */
  14457. class MeshLambertNodeMaterial extends NodeMaterial {
  14458. static get type() {
  14459. return 'MeshLambertNodeMaterial';
  14460. }
  14461. /**
  14462. * Constructs a new mesh lambert node material.
  14463. *
  14464. * @param {Object} [parameters] - The configuration parameter.
  14465. */
  14466. constructor( parameters ) {
  14467. super();
  14468. /**
  14469. * This flag can be used for type testing.
  14470. *
  14471. * @type {boolean}
  14472. * @readonly
  14473. * @default true
  14474. */
  14475. this.isMeshLambertNodeMaterial = true;
  14476. /**
  14477. * Set to `true` because lambert materials react on lights.
  14478. *
  14479. * @type {boolean}
  14480. * @default true
  14481. */
  14482. this.lights = true;
  14483. this.setDefaultValues( _defaultValues$8 );
  14484. this.setValues( parameters );
  14485. }
  14486. /**
  14487. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14488. * to implement the default environment mapping.
  14489. *
  14490. * @param {NodeBuilder} builder - The current node builder.
  14491. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14492. */
  14493. setupEnvironment( builder ) {
  14494. const envNode = super.setupEnvironment( builder );
  14495. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14496. }
  14497. /**
  14498. * Setups the lighting model.
  14499. *
  14500. * @return {PhongLightingModel} The lighting model.
  14501. */
  14502. setupLightingModel( /*builder*/ ) {
  14503. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  14504. }
  14505. }
  14506. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  14507. /**
  14508. * Node material version of {@link MeshPhongMaterial}.
  14509. *
  14510. * @augments NodeMaterial
  14511. */
  14512. class MeshPhongNodeMaterial extends NodeMaterial {
  14513. static get type() {
  14514. return 'MeshPhongNodeMaterial';
  14515. }
  14516. /**
  14517. * Constructs a new mesh lambert node material.
  14518. *
  14519. * @param {Object} [parameters] - The configuration parameter.
  14520. */
  14521. constructor( parameters ) {
  14522. super();
  14523. /**
  14524. * This flag can be used for type testing.
  14525. *
  14526. * @type {boolean}
  14527. * @readonly
  14528. * @default true
  14529. */
  14530. this.isMeshPhongNodeMaterial = true;
  14531. /**
  14532. * Set to `true` because phong materials react on lights.
  14533. *
  14534. * @type {boolean}
  14535. * @default true
  14536. */
  14537. this.lights = true;
  14538. /**
  14539. * The shininess of phong materials is by default inferred from the `shininess`
  14540. * property. This node property allows to overwrite the default
  14541. * and define the shininess with a node instead.
  14542. *
  14543. * If you don't want to overwrite the shininess but modify the existing
  14544. * value instead, use {@link materialShininess}.
  14545. *
  14546. * @type {?Node<float>}
  14547. * @default null
  14548. */
  14549. this.shininessNode = null;
  14550. /**
  14551. * The specular color of phong materials is by default inferred from the
  14552. * `specular` property. This node property allows to overwrite the default
  14553. * and define the specular color with a node instead.
  14554. *
  14555. * If you don't want to overwrite the specular color but modify the existing
  14556. * value instead, use {@link materialSpecular}.
  14557. *
  14558. * @type {?Node<vec3>}
  14559. * @default null
  14560. */
  14561. this.specularNode = null;
  14562. this.setDefaultValues( _defaultValues$7 );
  14563. this.setValues( parameters );
  14564. }
  14565. /**
  14566. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14567. * to implement the default environment mapping.
  14568. *
  14569. * @param {NodeBuilder} builder - The current node builder.
  14570. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14571. */
  14572. setupEnvironment( builder ) {
  14573. const envNode = super.setupEnvironment( builder );
  14574. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14575. }
  14576. /**
  14577. * Setups the lighting model.
  14578. *
  14579. * @return {PhongLightingModel} The lighting model.
  14580. */
  14581. setupLightingModel( /*builder*/ ) {
  14582. return new PhongLightingModel();
  14583. }
  14584. /**
  14585. * Setups the phong specific node variables.
  14586. *
  14587. * @param {NodeBuilder} builder - The current node builder.
  14588. */
  14589. setupVariants( /*builder*/ ) {
  14590. // SHININESS
  14591. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  14592. shininess.assign( shininessNode );
  14593. // SPECULAR COLOR
  14594. const specularNode = this.specularNode || materialSpecular;
  14595. specularColor.assign( specularNode );
  14596. }
  14597. copy( source ) {
  14598. this.shininessNode = source.shininessNode;
  14599. this.specularNode = source.specularNode;
  14600. return super.copy( source );
  14601. }
  14602. }
  14603. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  14604. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  14605. return float( 0 );
  14606. }
  14607. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  14608. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  14609. return geometryRoughness;
  14610. } );
  14611. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  14612. const { roughness } = inputs;
  14613. const geometryRoughness = getGeometryRoughness();
  14614. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  14615. roughnessFactor = roughnessFactor.add( geometryRoughness );
  14616. roughnessFactor = roughnessFactor.min( 1.0 );
  14617. return roughnessFactor;
  14618. } );
  14619. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  14620. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  14621. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  14622. const a2 = alpha.pow2();
  14623. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  14624. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  14625. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  14626. } ).setLayout( {
  14627. name: 'V_GGX_SmithCorrelated',
  14628. type: 'float',
  14629. inputs: [
  14630. { name: 'alpha', type: 'float' },
  14631. { name: 'dotNL', type: 'float' },
  14632. { name: 'dotNV', type: 'float' }
  14633. ]
  14634. } ); // validated
  14635. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  14636. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  14637. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  14638. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  14639. const v = div( 0.5, gv.add( gl ) );
  14640. return v.saturate();
  14641. } ).setLayout( {
  14642. name: 'V_GGX_SmithCorrelated_Anisotropic',
  14643. type: 'float',
  14644. inputs: [
  14645. { name: 'alphaT', type: 'float', qualifier: 'in' },
  14646. { name: 'alphaB', type: 'float', qualifier: 'in' },
  14647. { name: 'dotTV', type: 'float', qualifier: 'in' },
  14648. { name: 'dotBV', type: 'float', qualifier: 'in' },
  14649. { name: 'dotTL', type: 'float', qualifier: 'in' },
  14650. { name: 'dotBL', type: 'float', qualifier: 'in' },
  14651. { name: 'dotNV', type: 'float', qualifier: 'in' },
  14652. { name: 'dotNL', type: 'float', qualifier: 'in' }
  14653. ]
  14654. } );
  14655. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  14656. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  14657. // alpha is "roughness squared" in Disney’s reparameterization
  14658. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  14659. const a2 = alpha.pow2();
  14660. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  14661. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  14662. } ).setLayout( {
  14663. name: 'D_GGX',
  14664. type: 'float',
  14665. inputs: [
  14666. { name: 'alpha', type: 'float' },
  14667. { name: 'dotNH', type: 'float' }
  14668. ]
  14669. } ); // validated
  14670. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  14671. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  14672. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  14673. const a2 = alphaT.mul( alphaB );
  14674. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  14675. const v2 = v.dot( v );
  14676. const w2 = a2.div( v2 );
  14677. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  14678. } ).setLayout( {
  14679. name: 'D_GGX_Anisotropic',
  14680. type: 'float',
  14681. inputs: [
  14682. { name: 'alphaT', type: 'float', qualifier: 'in' },
  14683. { name: 'alphaB', type: 'float', qualifier: 'in' },
  14684. { name: 'dotNH', type: 'float', qualifier: 'in' },
  14685. { name: 'dotTH', type: 'float', qualifier: 'in' },
  14686. { name: 'dotBH', type: 'float', qualifier: 'in' }
  14687. ]
  14688. } );
  14689. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  14690. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  14691. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  14692. const normalView = inputs.normalView || transformedNormalView;
  14693. const alpha = roughness.pow2(); // UE4's roughness
  14694. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14695. const dotNL = normalView.dot( lightDirection ).clamp();
  14696. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  14697. const dotNH = normalView.dot( halfDir ).clamp();
  14698. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14699. let F = F_Schlick( { f0, f90, dotVH } );
  14700. let V, D;
  14701. if ( defined( USE_IRIDESCENCE ) ) {
  14702. F = iridescence.mix( F, f );
  14703. }
  14704. if ( defined( USE_ANISOTROPY ) ) {
  14705. const dotTL = anisotropyT.dot( lightDirection );
  14706. const dotTV = anisotropyT.dot( positionViewDirection );
  14707. const dotTH = anisotropyT.dot( halfDir );
  14708. const dotBL = anisotropyB.dot( lightDirection );
  14709. const dotBV = anisotropyB.dot( positionViewDirection );
  14710. const dotBH = anisotropyB.dot( halfDir );
  14711. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  14712. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  14713. } else {
  14714. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  14715. D = D_GGX( { alpha, dotNH } );
  14716. }
  14717. return F.mul( V ).mul( D );
  14718. } ); // validated
  14719. // Analytical approximation of the DFG LUT, one half of the
  14720. // split-sum approximation used in indirect specular lighting.
  14721. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  14722. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  14723. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  14724. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  14725. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  14726. const r = roughness.mul( c0 ).add( c1 );
  14727. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  14728. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  14729. return fab;
  14730. } ).setLayout( {
  14731. name: 'DFGApprox',
  14732. type: 'vec2',
  14733. inputs: [
  14734. { name: 'roughness', type: 'float' },
  14735. { name: 'dotNV', type: 'vec3' }
  14736. ]
  14737. } );
  14738. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  14739. const { dotNV, specularColor, specularF90, roughness } = inputs;
  14740. const fab = DFGApprox( { dotNV, roughness } );
  14741. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  14742. } );
  14743. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  14744. const x = dotVH.oneMinus().saturate();
  14745. const x2 = x.mul( x );
  14746. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  14747. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  14748. } ).setLayout( {
  14749. name: 'Schlick_to_F0',
  14750. type: 'vec3',
  14751. inputs: [
  14752. { name: 'f', type: 'vec3' },
  14753. { name: 'f90', type: 'float' },
  14754. { name: 'dotVH', type: 'float' }
  14755. ]
  14756. } );
  14757. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  14758. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  14759. const alpha = roughness.pow2();
  14760. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  14761. const invAlpha = float( 1.0 ).div( alpha );
  14762. const cos2h = dotNH.pow2();
  14763. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  14764. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  14765. } ).setLayout( {
  14766. name: 'D_Charlie',
  14767. type: 'float',
  14768. inputs: [
  14769. { name: 'roughness', type: 'float' },
  14770. { name: 'dotNH', type: 'float' }
  14771. ]
  14772. } );
  14773. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  14774. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  14775. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  14776. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  14777. } ).setLayout( {
  14778. name: 'V_Neubelt',
  14779. type: 'float',
  14780. inputs: [
  14781. { name: 'dotNV', type: 'float' },
  14782. { name: 'dotNL', type: 'float' }
  14783. ]
  14784. } );
  14785. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14786. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14787. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14788. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  14789. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14790. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  14791. const V = V_Neubelt( { dotNV, dotNL } );
  14792. return sheen.mul( D ).mul( V );
  14793. } );
  14794. // Rect Area Light
  14795. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  14796. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  14797. // code: https://github.com/selfshadow/ltc_code/
  14798. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  14799. const LUT_SIZE = 64.0;
  14800. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  14801. const LUT_BIAS = 0.5 / LUT_SIZE;
  14802. const dotNV = N.dot( V ).saturate();
  14803. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  14804. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  14805. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  14806. return uv;
  14807. } ).setLayout( {
  14808. name: 'LTC_Uv',
  14809. type: 'vec2',
  14810. inputs: [
  14811. { name: 'N', type: 'vec3' },
  14812. { name: 'V', type: 'vec3' },
  14813. { name: 'roughness', type: 'float' }
  14814. ]
  14815. } );
  14816. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  14817. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  14818. // An approximation of the form factor of a horizon-clipped rectangle.
  14819. const l = f.length();
  14820. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  14821. } ).setLayout( {
  14822. name: 'LTC_ClippedSphereFormFactor',
  14823. type: 'float',
  14824. inputs: [
  14825. { name: 'f', type: 'vec3' }
  14826. ]
  14827. } );
  14828. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  14829. const x = v1.dot( v2 );
  14830. const y = x.abs().toVar();
  14831. // rational polynomial approximation to theta / sin( theta ) / 2PI
  14832. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  14833. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  14834. const v = a.div( b );
  14835. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  14836. return v1.cross( v2 ).mul( theta_sintheta );
  14837. } ).setLayout( {
  14838. name: 'LTC_EdgeVectorFormFactor',
  14839. type: 'vec3',
  14840. inputs: [
  14841. { name: 'v1', type: 'vec3' },
  14842. { name: 'v2', type: 'vec3' }
  14843. ]
  14844. } );
  14845. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  14846. // bail if point is on back side of plane of light
  14847. // assumes ccw winding order of light vertices
  14848. const v1 = p1.sub( p0 ).toVar();
  14849. const v2 = p3.sub( p0 ).toVar();
  14850. const lightNormal = v1.cross( v2 );
  14851. const result = vec3().toVar();
  14852. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  14853. // construct orthonormal basis around N
  14854. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  14855. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  14856. // compute transform
  14857. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  14858. // transform rect
  14859. // & project rect onto sphere
  14860. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  14861. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  14862. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  14863. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  14864. // calculate vector form factor
  14865. const vectorFormFactor = vec3( 0 ).toVar();
  14866. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  14867. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  14868. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  14869. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  14870. // adjust for horizon clipping
  14871. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  14872. } );
  14873. return result;
  14874. } ).setLayout( {
  14875. name: 'LTC_Evaluate',
  14876. type: 'vec3',
  14877. inputs: [
  14878. { name: 'N', type: 'vec3' },
  14879. { name: 'V', type: 'vec3' },
  14880. { name: 'P', type: 'vec3' },
  14881. { name: 'mInv', type: 'mat3' },
  14882. { name: 'p0', type: 'vec3' },
  14883. { name: 'p1', type: 'vec3' },
  14884. { name: 'p2', type: 'vec3' },
  14885. { name: 'p3', type: 'vec3' }
  14886. ]
  14887. } );
  14888. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  14889. // bail if point is on back side of plane of light
  14890. // assumes ccw winding order of light vertices
  14891. const v1 = p1.sub( p0 ).toVar();
  14892. const v2 = p3.sub( p0 ).toVar();
  14893. const lightNormal = v1.cross( v2 );
  14894. const result = vec3().toVar();
  14895. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  14896. // transform rect
  14897. // & project rect onto sphere
  14898. const coords0 = p0.sub( P ).normalize().toVar();
  14899. const coords1 = p1.sub( P ).normalize().toVar();
  14900. const coords2 = p2.sub( P ).normalize().toVar();
  14901. const coords3 = p3.sub( P ).normalize().toVar();
  14902. // calculate vector form factor
  14903. const vectorFormFactor = vec3( 0 ).toVar();
  14904. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  14905. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  14906. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  14907. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  14908. // adjust for horizon clipping
  14909. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  14910. } );
  14911. return result;
  14912. } ).setLayout( {
  14913. name: 'LTC_Evaluate',
  14914. type: 'vec3',
  14915. inputs: [
  14916. { name: 'P', type: 'vec3' },
  14917. { name: 'p0', type: 'vec3' },
  14918. { name: 'p1', type: 'vec3' },
  14919. { name: 'p2', type: 'vec3' },
  14920. { name: 'p3', type: 'vec3' }
  14921. ]
  14922. } );
  14923. // Mipped Bicubic Texture Filtering by N8
  14924. // https://www.shadertoy.com/view/Dl2SDW
  14925. const bC = 1.0 / 6.0;
  14926. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  14927. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  14928. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  14929. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  14930. const g0 = ( a ) => w0( a ).add( w1( a ) );
  14931. const g1 = ( a ) => w2( a ).add( w3( a ) );
  14932. // h0 and h1 are the two offset functions
  14933. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  14934. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  14935. const bicubic = ( textureNode, texelSize, lod ) => {
  14936. const uv = textureNode.uvNode;
  14937. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  14938. const iuv = floor( uvScaled );
  14939. const fuv = fract( uvScaled );
  14940. const g0x = g0( fuv.x );
  14941. const g1x = g1( fuv.x );
  14942. const h0x = h0( fuv.x );
  14943. const h1x = h1( fuv.x );
  14944. const h0y = h0( fuv.y );
  14945. const h1y = h1( fuv.y );
  14946. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  14947. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  14948. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  14949. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  14950. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  14951. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  14952. return a.add( b );
  14953. };
  14954. /**
  14955. * Applies mipped bicubic texture filtering to the given texture node.
  14956. *
  14957. * @tsl
  14958. * @function
  14959. * @param {TextureNode} textureNode - The texture node that should be filtered.
  14960. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  14961. * @return {Node} The filtered texture sample.
  14962. */
  14963. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  14964. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  14965. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  14966. const fLodSizeInv = div( 1.0, fLodSize );
  14967. const cLodSizeInv = div( 1.0, cLodSize );
  14968. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  14969. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  14970. return fract( lodNode ).mix( fSample, cSample );
  14971. } );
  14972. //
  14973. // Transmission
  14974. //
  14975. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  14976. // Direction of refracted light.
  14977. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  14978. // Compute rotation-independent scaling of the model matrix.
  14979. const modelScale = vec3(
  14980. length( modelMatrix[ 0 ].xyz ),
  14981. length( modelMatrix[ 1 ].xyz ),
  14982. length( modelMatrix[ 2 ].xyz )
  14983. );
  14984. // The thickness is specified in local space.
  14985. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  14986. } ).setLayout( {
  14987. name: 'getVolumeTransmissionRay',
  14988. type: 'vec3',
  14989. inputs: [
  14990. { name: 'n', type: 'vec3' },
  14991. { name: 'v', type: 'vec3' },
  14992. { name: 'thickness', type: 'float' },
  14993. { name: 'ior', type: 'float' },
  14994. { name: 'modelMatrix', type: 'mat4' }
  14995. ]
  14996. } );
  14997. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  14998. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  14999. // an IOR of 1.5 results in the default amount of microfacet refraction.
  15000. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  15001. } ).setLayout( {
  15002. name: 'applyIorToRoughness',
  15003. type: 'float',
  15004. inputs: [
  15005. { name: 'roughness', type: 'float' },
  15006. { name: 'ior', type: 'float' }
  15007. ]
  15008. } );
  15009. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  15010. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  15011. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  15012. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  15013. const transmissionSample = vTexture.sample( fragCoord );
  15014. //const transmissionSample = viewportMipTexture( fragCoord );
  15015. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  15016. return textureBicubic( transmissionSample, lod );
  15017. } );
  15018. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  15019. If( attenuationDistance.notEqual( 0 ), () => {
  15020. // Compute light attenuation using Beer's law.
  15021. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  15022. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  15023. return transmittance;
  15024. } );
  15025. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  15026. return vec3( 1.0 );
  15027. } ).setLayout( {
  15028. name: 'volumeAttenuation',
  15029. type: 'vec3',
  15030. inputs: [
  15031. { name: 'transmissionDistance', type: 'float' },
  15032. { name: 'attenuationColor', type: 'vec3' },
  15033. { name: 'attenuationDistance', type: 'float' }
  15034. ]
  15035. } );
  15036. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  15037. let transmittedLight, transmittance;
  15038. if ( dispersion ) {
  15039. transmittedLight = vec4().toVar();
  15040. transmittance = vec3().toVar();
  15041. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  15042. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  15043. Loop( { start: 0, end: 3 }, ( { i } ) => {
  15044. const ior = iors.element( i );
  15045. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15046. const refractedRayExit = position.add( transmissionRay );
  15047. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15048. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15049. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15050. refractionCoords.addAssign( 1.0 );
  15051. refractionCoords.divAssign( 2.0 );
  15052. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15053. // Sample framebuffer to get pixel the refracted ray hits.
  15054. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  15055. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  15056. transmittedLight.a.addAssign( transmissionSample.a );
  15057. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  15058. } );
  15059. transmittedLight.a.divAssign( 3.0 );
  15060. } else {
  15061. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15062. const refractedRayExit = position.add( transmissionRay );
  15063. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15064. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15065. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15066. refractionCoords.addAssign( 1.0 );
  15067. refractionCoords.divAssign( 2.0 );
  15068. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15069. // Sample framebuffer to get pixel the refracted ray hits.
  15070. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  15071. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  15072. }
  15073. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  15074. const dotNV = n.dot( v ).clamp();
  15075. // Get the specular component.
  15076. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  15077. dotNV,
  15078. specularColor,
  15079. specularF90,
  15080. roughness
  15081. } ) );
  15082. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  15083. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  15084. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  15085. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  15086. } );
  15087. //
  15088. // Iridescence
  15089. //
  15090. // XYZ to linear-sRGB color space
  15091. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  15092. 3.2404542, -0.969266, 0.0556434,
  15093. -1.5371385, 1.8760108, -0.2040259,
  15094. -0.4985314, 0.0415560, 1.0572252
  15095. );
  15096. // Assume air interface for top
  15097. // Note: We don't handle the case fresnel0 == 1
  15098. const Fresnel0ToIor = ( fresnel0 ) => {
  15099. const sqrtF0 = fresnel0.sqrt();
  15100. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  15101. };
  15102. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  15103. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  15104. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  15105. };
  15106. // Fresnel equations for dielectric/dielectric interfaces.
  15107. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  15108. // Evaluation XYZ sensitivity curves in Fourier space
  15109. const evalSensitivity = ( OPD, shift ) => {
  15110. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  15111. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  15112. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  15113. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  15114. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( -45282e5 ).exp() );
  15115. 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() );
  15116. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  15117. const rgb = XYZ_TO_REC709.mul( xyz );
  15118. return rgb;
  15119. };
  15120. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  15121. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  15122. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  15123. // Evaluate the cosTheta on the base layer (Snell law)
  15124. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  15125. // Handle TIR:
  15126. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  15127. If( cosTheta2Sq.lessThan( 0 ), () => {
  15128. return vec3( 1.0 );
  15129. } );
  15130. const cosTheta2 = cosTheta2Sq.sqrt();
  15131. // First interface
  15132. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  15133. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  15134. //const R21 = R12;
  15135. const T121 = R12.oneMinus();
  15136. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  15137. const phi21 = float( Math.PI ).sub( phi12 );
  15138. // Second interface
  15139. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  15140. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  15141. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  15142. const phi23 = vec3(
  15143. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15144. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15145. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  15146. );
  15147. // Phase shift
  15148. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  15149. const phi = vec3( phi21 ).add( phi23 );
  15150. // Compound terms
  15151. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  15152. const r123 = R123.sqrt();
  15153. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  15154. // Reflectance term for m = 0 (DC term amplitude)
  15155. const C0 = R12.add( Rs );
  15156. const I = C0.toVar();
  15157. // Reflectance term for m > 0 (pairs of diracs)
  15158. const Cm = Rs.sub( T121 ).toVar();
  15159. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  15160. Cm.mulAssign( r123 );
  15161. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  15162. I.addAssign( Cm.mul( Sm ) );
  15163. } );
  15164. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  15165. return I.max( vec3( 0.0 ) );
  15166. } ).setLayout( {
  15167. name: 'evalIridescence',
  15168. type: 'vec3',
  15169. inputs: [
  15170. { name: 'outsideIOR', type: 'float' },
  15171. { name: 'eta2', type: 'float' },
  15172. { name: 'cosTheta1', type: 'float' },
  15173. { name: 'thinFilmThickness', type: 'float' },
  15174. { name: 'baseF0', type: 'vec3' }
  15175. ]
  15176. } );
  15177. //
  15178. // Sheen
  15179. //
  15180. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  15181. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  15182. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  15183. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  15184. const dotNV = normal.dot( viewDir ).saturate();
  15185. const r2 = roughness.pow2();
  15186. const a = select(
  15187. roughness.lessThan( 0.25 ),
  15188. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  15189. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  15190. );
  15191. const b = select(
  15192. roughness.lessThan( 0.25 ),
  15193. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  15194. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  15195. );
  15196. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  15197. return DG.mul( 1.0 / Math.PI ).saturate();
  15198. } );
  15199. const clearcoatF0 = vec3( 0.04 );
  15200. const clearcoatF90 = float( 1 );
  15201. /**
  15202. * Represents the lighting model for a PBR material.
  15203. *
  15204. * @augments LightingModel
  15205. */
  15206. class PhysicalLightingModel extends LightingModel {
  15207. /**
  15208. * Constructs a new physical lighting model.
  15209. *
  15210. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15211. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15212. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15213. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15214. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15215. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15216. */
  15217. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  15218. super();
  15219. /**
  15220. * Whether clearcoat is supported or not.
  15221. *
  15222. * @type {boolean}
  15223. * @default false
  15224. */
  15225. this.clearcoat = clearcoat;
  15226. /**
  15227. * Whether sheen is supported or not.
  15228. *
  15229. * @type {boolean}
  15230. * @default false
  15231. */
  15232. this.sheen = sheen;
  15233. /**
  15234. * Whether iridescence is supported or not.
  15235. *
  15236. * @type {boolean}
  15237. * @default false
  15238. */
  15239. this.iridescence = iridescence;
  15240. /**
  15241. * Whether anisotropy is supported or not.
  15242. *
  15243. * @type {boolean}
  15244. * @default false
  15245. */
  15246. this.anisotropy = anisotropy;
  15247. /**
  15248. * Whether transmission is supported or not.
  15249. *
  15250. * @type {boolean}
  15251. * @default false
  15252. */
  15253. this.transmission = transmission;
  15254. /**
  15255. * Whether dispersion is supported or not.
  15256. *
  15257. * @type {boolean}
  15258. * @default false
  15259. */
  15260. this.dispersion = dispersion;
  15261. /**
  15262. * The clear coat radiance.
  15263. *
  15264. * @type {?Node}
  15265. * @default null
  15266. */
  15267. this.clearcoatRadiance = null;
  15268. /**
  15269. * The clear coat specular direct.
  15270. *
  15271. * @type {?Node}
  15272. * @default null
  15273. */
  15274. this.clearcoatSpecularDirect = null;
  15275. /**
  15276. * The clear coat specular indirect.
  15277. *
  15278. * @type {?Node}
  15279. * @default null
  15280. */
  15281. this.clearcoatSpecularIndirect = null;
  15282. /**
  15283. * The sheen specular direct.
  15284. *
  15285. * @type {?Node}
  15286. * @default null
  15287. */
  15288. this.sheenSpecularDirect = null;
  15289. /**
  15290. * The sheen specular indirect.
  15291. *
  15292. * @type {?Node}
  15293. * @default null
  15294. */
  15295. this.sheenSpecularIndirect = null;
  15296. /**
  15297. * The iridescence Fresnel.
  15298. *
  15299. * @type {?Node}
  15300. * @default null
  15301. */
  15302. this.iridescenceFresnel = null;
  15303. /**
  15304. * The iridescence F0.
  15305. *
  15306. * @type {?Node}
  15307. * @default null
  15308. */
  15309. this.iridescenceF0 = null;
  15310. }
  15311. /**
  15312. * Depending on what features are requested, the method prepares certain node variables
  15313. * which are later used for lighting computations.
  15314. *
  15315. * @param {NodeBuilder} builder - The current node builder.
  15316. */
  15317. start( builder ) {
  15318. if ( this.clearcoat === true ) {
  15319. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  15320. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  15321. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  15322. }
  15323. if ( this.sheen === true ) {
  15324. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  15325. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  15326. }
  15327. if ( this.iridescence === true ) {
  15328. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  15329. this.iridescenceFresnel = evalIridescence( {
  15330. outsideIOR: float( 1.0 ),
  15331. eta2: iridescenceIOR,
  15332. cosTheta1: dotNVi,
  15333. thinFilmThickness: iridescenceThickness,
  15334. baseF0: specularColor
  15335. } );
  15336. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  15337. }
  15338. if ( this.transmission === true ) {
  15339. const position = positionWorld;
  15340. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  15341. const n = transformedNormalWorld;
  15342. const context = builder.context;
  15343. context.backdrop = getIBLVolumeRefraction(
  15344. n,
  15345. v,
  15346. roughness,
  15347. diffuseColor,
  15348. specularColor,
  15349. specularF90, // specularF90
  15350. position, // positionWorld
  15351. modelWorldMatrix, // modelMatrix
  15352. cameraViewMatrix, // viewMatrix
  15353. cameraProjectionMatrix, // projMatrix
  15354. ior,
  15355. thickness,
  15356. attenuationColor,
  15357. attenuationDistance,
  15358. this.dispersion ? dispersion : null
  15359. );
  15360. context.backdropAlpha = transmission;
  15361. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  15362. }
  15363. super.start( builder );
  15364. }
  15365. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  15366. // Approximates multi-scattering in order to preserve energy.
  15367. // http://www.jcgt.org/published/0008/01/03/
  15368. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  15369. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15370. const fab = DFGApprox( { roughness, dotNV } );
  15371. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  15372. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15373. const Ess = fab.x.add( fab.y );
  15374. const Ems = Ess.oneMinus();
  15375. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  15376. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  15377. singleScatter.addAssign( FssEss );
  15378. multiScatter.addAssign( Fms.mul( Ems ) );
  15379. }
  15380. /**
  15381. * Implements the direct light.
  15382. *
  15383. * @param {Object} lightData - The light data.
  15384. * @param {NodeBuilder} builder - The current node builder.
  15385. */
  15386. direct( { lightDirection, lightColor, reflectedLight } ) {
  15387. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  15388. const irradiance = dotNL.mul( lightColor );
  15389. if ( this.sheen === true ) {
  15390. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  15391. }
  15392. if ( this.clearcoat === true ) {
  15393. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  15394. const ccIrradiance = dotNLcc.mul( lightColor );
  15395. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  15396. }
  15397. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15398. 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 } ) ) );
  15399. }
  15400. /**
  15401. * This method is intended for implementing the direct light term for
  15402. * rect area light nodes.
  15403. *
  15404. * @param {Object} input - The input data.
  15405. * @param {NodeBuilder} builder - The current node builder.
  15406. */
  15407. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  15408. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  15409. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  15410. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  15411. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  15412. const N = transformedNormalView;
  15413. const V = positionViewDirection;
  15414. const P = positionView.toVar();
  15415. const uv = LTC_Uv( { N, V, roughness } );
  15416. const t1 = ltc_1.sample( uv ).toVar();
  15417. const t2 = ltc_2.sample( uv ).toVar();
  15418. const mInv = mat3(
  15419. vec3( t1.x, 0, t1.y ),
  15420. vec3( 0, 1, 0 ),
  15421. vec3( t1.z, 0, t1.w )
  15422. ).toVar();
  15423. // LTC Fresnel Approximation by Stephen Hill
  15424. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  15425. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  15426. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  15427. 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 } ) ) );
  15428. }
  15429. /**
  15430. * Implements the indirect lighting.
  15431. *
  15432. * @param {NodeBuilder} builder - The current node builder.
  15433. */
  15434. indirect( builder ) {
  15435. this.indirectDiffuse( builder );
  15436. this.indirectSpecular( builder );
  15437. this.ambientOcclusion( builder );
  15438. }
  15439. /**
  15440. * Implements the indirect diffuse term.
  15441. *
  15442. * @param {NodeBuilder} builder - The current node builder.
  15443. */
  15444. indirectDiffuse( builder ) {
  15445. const { irradiance, reflectedLight } = builder.context;
  15446. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15447. }
  15448. /**
  15449. * Implements the indirect specular term.
  15450. *
  15451. * @param {NodeBuilder} builder - The current node builder.
  15452. */
  15453. indirectSpecular( builder ) {
  15454. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  15455. if ( this.sheen === true ) {
  15456. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  15457. sheen,
  15458. IBLSheenBRDF( {
  15459. normal: transformedNormalView,
  15460. viewDir: positionViewDirection,
  15461. roughness: sheenRoughness
  15462. } )
  15463. ) );
  15464. }
  15465. if ( this.clearcoat === true ) {
  15466. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15467. const clearcoatEnv = EnvironmentBRDF( {
  15468. dotNV: dotNVcc,
  15469. specularColor: clearcoatF0,
  15470. specularF90: clearcoatF90,
  15471. roughness: clearcoatRoughness
  15472. } );
  15473. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  15474. }
  15475. // Both indirect specular and indirect diffuse light accumulate here
  15476. const singleScattering = vec3().toVar( 'singleScattering' );
  15477. const multiScattering = vec3().toVar( 'multiScattering' );
  15478. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  15479. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  15480. const totalScattering = singleScattering.add( multiScattering );
  15481. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  15482. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  15483. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  15484. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  15485. }
  15486. /**
  15487. * Implements the ambient occlusion term.
  15488. *
  15489. * @param {NodeBuilder} builder - The current node builder.
  15490. */
  15491. ambientOcclusion( builder ) {
  15492. const { ambientOcclusion, reflectedLight } = builder.context;
  15493. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15494. const aoNV = dotNV.add( ambientOcclusion );
  15495. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  15496. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  15497. if ( this.clearcoat === true ) {
  15498. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  15499. }
  15500. if ( this.sheen === true ) {
  15501. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  15502. }
  15503. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15504. reflectedLight.indirectSpecular.mulAssign( aoNode );
  15505. }
  15506. /**
  15507. * Used for final lighting accumulations depending on the requested features.
  15508. *
  15509. * @param {NodeBuilder} builder - The current node builder.
  15510. */
  15511. finish( { context } ) {
  15512. const { outgoingLight } = context;
  15513. if ( this.clearcoat === true ) {
  15514. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15515. const Fcc = F_Schlick( {
  15516. dotVH: dotNVcc,
  15517. f0: clearcoatF0,
  15518. f90: clearcoatF90
  15519. } );
  15520. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  15521. outgoingLight.assign( clearcoatLight );
  15522. }
  15523. if ( this.sheen === true ) {
  15524. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  15525. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  15526. outgoingLight.assign( sheenLight );
  15527. }
  15528. }
  15529. }
  15530. // These defines must match with PMREMGenerator
  15531. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  15532. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  15533. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  15534. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  15535. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  15536. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  15537. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  15538. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  15539. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  15540. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  15541. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  15542. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  15543. // These shader functions convert between the UV coordinates of a single face of
  15544. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  15545. // sampling a textureCube (not generally normalized ).
  15546. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  15547. const absDirection = vec3( abs( direction ) ).toVar();
  15548. const face = float( -1 ).toVar();
  15549. If( absDirection.x.greaterThan( absDirection.z ), () => {
  15550. If( absDirection.x.greaterThan( absDirection.y ), () => {
  15551. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  15552. } ).Else( () => {
  15553. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15554. } );
  15555. } ).Else( () => {
  15556. If( absDirection.z.greaterThan( absDirection.y ), () => {
  15557. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  15558. } ).Else( () => {
  15559. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15560. } );
  15561. } );
  15562. return face;
  15563. } ).setLayout( {
  15564. name: 'getFace',
  15565. type: 'float',
  15566. inputs: [
  15567. { name: 'direction', type: 'vec3' }
  15568. ]
  15569. } );
  15570. // RH coordinate system; PMREM face-indexing convention
  15571. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  15572. const uv = vec2().toVar();
  15573. If( face.equal( 0.0 ), () => {
  15574. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  15575. } ).ElseIf( face.equal( 1.0 ), () => {
  15576. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  15577. } ).ElseIf( face.equal( 2.0 ), () => {
  15578. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  15579. } ).ElseIf( face.equal( 3.0 ), () => {
  15580. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  15581. } ).ElseIf( face.equal( 4.0 ), () => {
  15582. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  15583. } ).Else( () => {
  15584. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  15585. } );
  15586. return mul( 0.5, uv.add( 1.0 ) );
  15587. } ).setLayout( {
  15588. name: 'getUV',
  15589. type: 'vec2',
  15590. inputs: [
  15591. { name: 'direction', type: 'vec3' },
  15592. { name: 'face', type: 'float' }
  15593. ]
  15594. } );
  15595. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  15596. const mip = float( 0.0 ).toVar();
  15597. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  15598. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  15599. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  15600. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  15601. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  15602. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  15603. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  15604. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  15605. } ).Else( () => {
  15606. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  15607. } );
  15608. return mip;
  15609. } ).setLayout( {
  15610. name: 'roughnessToMip',
  15611. type: 'float',
  15612. inputs: [
  15613. { name: 'roughness', type: 'float' }
  15614. ]
  15615. } );
  15616. // RH coordinate system; PMREM face-indexing convention
  15617. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  15618. const uv = uv_immutable.toVar();
  15619. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  15620. const direction = vec3( uv, 1.0 ).toVar();
  15621. If( face.equal( 0.0 ), () => {
  15622. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  15623. } ).ElseIf( face.equal( 1.0 ), () => {
  15624. direction.assign( direction.xzy );
  15625. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  15626. } ).ElseIf( face.equal( 2.0 ), () => {
  15627. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  15628. } ).ElseIf( face.equal( 3.0 ), () => {
  15629. direction.assign( direction.zyx );
  15630. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  15631. } ).ElseIf( face.equal( 4.0 ), () => {
  15632. direction.assign( direction.xzy );
  15633. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  15634. } ).ElseIf( face.equal( 5.0 ), () => {
  15635. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  15636. } );
  15637. return direction;
  15638. } ).setLayout( {
  15639. name: 'getDirection',
  15640. type: 'vec3',
  15641. inputs: [
  15642. { name: 'uv', type: 'vec2' },
  15643. { name: 'face', type: 'float' }
  15644. ]
  15645. } );
  15646. //
  15647. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  15648. const roughness = float( roughness_immutable );
  15649. const sampleDir = vec3( sampleDir_immutable );
  15650. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  15651. const mipF = fract( mip );
  15652. const mipInt = floor( mip );
  15653. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  15654. If( mipF.notEqual( 0.0 ), () => {
  15655. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  15656. color0.assign( mix( color0, color1, mipF ) );
  15657. } );
  15658. return color0;
  15659. } );
  15660. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  15661. const mipInt = float( mipInt_immutable ).toVar();
  15662. const direction = vec3( direction_immutable );
  15663. const face = float( getFace( direction ) ).toVar();
  15664. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  15665. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  15666. const faceSize = float( exp2( mipInt ) ).toVar();
  15667. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  15668. If( face.greaterThan( 2.0 ), () => {
  15669. uv.y.addAssign( faceSize );
  15670. face.subAssign( 3.0 );
  15671. } );
  15672. uv.x.addAssign( face.mul( faceSize ) );
  15673. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  15674. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  15675. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  15676. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  15677. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  15678. } );
  15679. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  15680. const cosTheta = cos( theta );
  15681. // Rodrigues' axis-angle rotation
  15682. const sampleDirection = outputDirection.mul( cosTheta )
  15683. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  15684. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  15685. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  15686. } );
  15687. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  15688. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  15689. If( axis.equal( vec3( 0.0 ) ), () => {
  15690. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  15691. } );
  15692. axis.assign( normalize( axis ) );
  15693. const gl_FragColor = vec3().toVar();
  15694. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15695. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  15696. If( i.greaterThanEqual( samples ), () => {
  15697. Break();
  15698. } );
  15699. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  15700. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( -1 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15701. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  15702. } );
  15703. return vec4( gl_FragColor, 1 );
  15704. } );
  15705. const LOD_MIN = 4;
  15706. // The standard deviations (radians) associated with the extra mips. These are
  15707. // chosen to approximate a Trowbridge-Reitz distribution function times the
  15708. // geometric shadowing function. These sigma values squared must match the
  15709. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  15710. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  15711. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  15712. // samples and exit early, but not recompile the shader.
  15713. const MAX_SAMPLES = 20;
  15714. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  15715. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  15716. const _clearColor$2 = /*@__PURE__*/ new Color();
  15717. let _oldTarget = null;
  15718. let _oldActiveCubeFace = 0;
  15719. let _oldActiveMipmapLevel = 0;
  15720. // Golden Ratio
  15721. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  15722. const INV_PHI = 1 / PHI;
  15723. // Vertices of a dodecahedron (except the opposites, which represent the
  15724. // same axis), used as axis directions evenly spread on a sphere.
  15725. const _axisDirections = [
  15726. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  15727. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  15728. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  15729. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  15730. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  15731. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  15732. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  15733. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  15734. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  15735. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  15736. ];
  15737. const _origin = /*@__PURE__*/ new Vector3();
  15738. // maps blur materials to their uniforms dictionary
  15739. const _uniformsMap = new WeakMap();
  15740. // WebGPU Face indices
  15741. const _faceLib = [
  15742. 3, 1, 5,
  15743. 0, 4, 2
  15744. ];
  15745. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  15746. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  15747. /**
  15748. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  15749. * (PMREM) from a cubeMap environment texture. This allows different levels of
  15750. * blur to be quickly accessed based on material roughness. It is packed into a
  15751. * special CubeUV format that allows us to perform custom interpolation so that
  15752. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  15753. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  15754. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  15755. * higher roughness levels. In this way we maintain resolution to smoothly
  15756. * interpolate diffuse lighting while limiting sampling computation.
  15757. *
  15758. * Paper: Fast, Accurate Image-Based Lighting:
  15759. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  15760. */
  15761. class PMREMGenerator {
  15762. /**
  15763. * Constructs a new PMREM generator.
  15764. *
  15765. * @param {Renderer} renderer - The renderer.
  15766. */
  15767. constructor( renderer ) {
  15768. this._renderer = renderer;
  15769. this._pingPongRenderTarget = null;
  15770. this._lodMax = 0;
  15771. this._cubeSize = 0;
  15772. this._lodPlanes = [];
  15773. this._sizeLods = [];
  15774. this._sigmas = [];
  15775. this._lodMeshes = [];
  15776. this._blurMaterial = null;
  15777. this._cubemapMaterial = null;
  15778. this._equirectMaterial = null;
  15779. this._backgroundBox = null;
  15780. }
  15781. get _hasInitialized() {
  15782. return this._renderer.hasInitialized();
  15783. }
  15784. /**
  15785. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15786. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15787. * in radians to be applied to the scene before PMREM generation. Optional near
  15788. * and far planes ensure the scene is rendered in its entirety.
  15789. *
  15790. * @param {Scene} scene - The scene to be captured.
  15791. * @param {number} [sigma=0] - The blur radius in radians.
  15792. * @param {number} [near=0.1] - The near plane distance.
  15793. * @param {number} [far=100] - The far plane distance.
  15794. * @param {Object} [options={}] - The configuration options.
  15795. * @param {number} [options.size=256] - The texture size of the PMREM.
  15796. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  15797. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  15798. * @return {RenderTarget} The resulting PMREM.
  15799. * @see {@link PMREMGenerator#fromSceneAsync}
  15800. */
  15801. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  15802. const {
  15803. size = 256,
  15804. position = _origin,
  15805. renderTarget = null,
  15806. } = options;
  15807. this._setSize( size );
  15808. if ( this._hasInitialized === false ) {
  15809. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  15810. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15811. options.renderTarget = cubeUVRenderTarget;
  15812. this.fromSceneAsync( scene, sigma, near, far, options );
  15813. return cubeUVRenderTarget;
  15814. }
  15815. _oldTarget = this._renderer.getRenderTarget();
  15816. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15817. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15818. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15819. cubeUVRenderTarget.depthBuffer = true;
  15820. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  15821. if ( sigma > 0 ) {
  15822. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  15823. }
  15824. this._applyPMREM( cubeUVRenderTarget );
  15825. this._cleanup( cubeUVRenderTarget );
  15826. return cubeUVRenderTarget;
  15827. }
  15828. /**
  15829. * Generates a PMREM from a supplied Scene, which can be faster than using an
  15830. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  15831. * in radians to be applied to the scene before PMREM generation. Optional near
  15832. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  15833. * is placed at the origin).
  15834. *
  15835. * @param {Scene} scene - The scene to be captured.
  15836. * @param {number} [sigma=0] - The blur radius in radians.
  15837. * @param {number} [near=0.1] - The near plane distance.
  15838. * @param {number} [far=100] - The far plane distance.
  15839. * @param {Object} [options={}] - The configuration options.
  15840. * @param {number} [options.size=256] - The texture size of the PMREM.
  15841. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  15842. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  15843. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  15844. * @see {@link PMREMGenerator#fromScene}
  15845. */
  15846. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  15847. if ( this._hasInitialized === false ) await this._renderer.init();
  15848. return this.fromScene( scene, sigma, near, far, options );
  15849. }
  15850. /**
  15851. * Generates a PMREM from an equirectangular texture, which can be either LDR
  15852. * or HDR. The ideal input image size is 1k (1024 x 512),
  15853. * as this matches best with the 256 x 256 cubemap output.
  15854. *
  15855. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  15856. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15857. * @return {RenderTarget} The resulting PMREM.
  15858. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  15859. */
  15860. fromEquirectangular( equirectangular, renderTarget = null ) {
  15861. if ( this._hasInitialized === false ) {
  15862. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  15863. this._setSizeFromTexture( equirectangular );
  15864. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15865. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  15866. return cubeUVRenderTarget;
  15867. }
  15868. return this._fromTexture( equirectangular, renderTarget );
  15869. }
  15870. /**
  15871. * Generates a PMREM from an equirectangular texture, which can be either LDR
  15872. * or HDR. The ideal input image size is 1k (1024 x 512),
  15873. * as this matches best with the 256 x 256 cubemap output.
  15874. *
  15875. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  15876. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15877. * @return {Promise<RenderTarget>} The resulting PMREM.
  15878. * @see {@link PMREMGenerator#fromEquirectangular}
  15879. */
  15880. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  15881. if ( this._hasInitialized === false ) await this._renderer.init();
  15882. return this._fromTexture( equirectangular, renderTarget );
  15883. }
  15884. /**
  15885. * Generates a PMREM from an cubemap texture, which can be either LDR
  15886. * or HDR. The ideal input cube size is 256 x 256,
  15887. * as this matches best with the 256 x 256 cubemap output.
  15888. *
  15889. * @param {Texture} cubemap - The cubemap texture to be converted.
  15890. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15891. * @return {RenderTarget} The resulting PMREM.
  15892. * @see {@link PMREMGenerator#fromCubemapAsync}
  15893. */
  15894. fromCubemap( cubemap, renderTarget = null ) {
  15895. if ( this._hasInitialized === false ) {
  15896. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  15897. this._setSizeFromTexture( cubemap );
  15898. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15899. this.fromCubemapAsync( cubemap, renderTarget );
  15900. return cubeUVRenderTarget;
  15901. }
  15902. return this._fromTexture( cubemap, renderTarget );
  15903. }
  15904. /**
  15905. * Generates a PMREM from an cubemap texture, which can be either LDR
  15906. * or HDR. The ideal input cube size is 256 x 256,
  15907. * with the 256 x 256 cubemap output.
  15908. *
  15909. * @param {Texture} cubemap - The cubemap texture to be converted.
  15910. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  15911. * @return {Promise<RenderTarget>} The resulting PMREM.
  15912. * @see {@link PMREMGenerator#fromCubemap}
  15913. */
  15914. async fromCubemapAsync( cubemap, renderTarget = null ) {
  15915. if ( this._hasInitialized === false ) await this._renderer.init();
  15916. return this._fromTexture( cubemap, renderTarget );
  15917. }
  15918. /**
  15919. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  15920. * your texture's network fetch for increased concurrency.
  15921. *
  15922. * @returns {Promise}
  15923. */
  15924. async compileCubemapShader() {
  15925. if ( this._cubemapMaterial === null ) {
  15926. this._cubemapMaterial = _getCubemapMaterial();
  15927. await this._compileMaterial( this._cubemapMaterial );
  15928. }
  15929. }
  15930. /**
  15931. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  15932. * your texture's network fetch for increased concurrency.
  15933. *
  15934. * @returns {Promise}
  15935. */
  15936. async compileEquirectangularShader() {
  15937. if ( this._equirectMaterial === null ) {
  15938. this._equirectMaterial = _getEquirectMaterial();
  15939. await this._compileMaterial( this._equirectMaterial );
  15940. }
  15941. }
  15942. /**
  15943. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  15944. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  15945. * one of them will cause any others to also become unusable.
  15946. */
  15947. dispose() {
  15948. this._dispose();
  15949. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  15950. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  15951. if ( this._backgroundBox !== null ) {
  15952. this._backgroundBox.geometry.dispose();
  15953. this._backgroundBox.material.dispose();
  15954. }
  15955. }
  15956. // private interface
  15957. _setSizeFromTexture( texture ) {
  15958. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  15959. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  15960. } else { // Equirectangular
  15961. this._setSize( texture.image.width / 4 );
  15962. }
  15963. }
  15964. _setSize( cubeSize ) {
  15965. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  15966. this._cubeSize = Math.pow( 2, this._lodMax );
  15967. }
  15968. _dispose() {
  15969. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  15970. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  15971. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  15972. this._lodPlanes[ i ].dispose();
  15973. }
  15974. }
  15975. _cleanup( outputTarget ) {
  15976. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  15977. outputTarget.scissorTest = false;
  15978. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  15979. }
  15980. _fromTexture( texture, renderTarget ) {
  15981. this._setSizeFromTexture( texture );
  15982. _oldTarget = this._renderer.getRenderTarget();
  15983. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  15984. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  15985. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  15986. this._textureToCubeUV( texture, cubeUVRenderTarget );
  15987. this._applyPMREM( cubeUVRenderTarget );
  15988. this._cleanup( cubeUVRenderTarget );
  15989. return cubeUVRenderTarget;
  15990. }
  15991. _allocateTargets() {
  15992. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  15993. const height = 4 * this._cubeSize;
  15994. const params = {
  15995. magFilter: LinearFilter,
  15996. minFilter: LinearFilter,
  15997. generateMipmaps: false,
  15998. type: HalfFloatType,
  15999. format: RGBAFormat,
  16000. colorSpace: LinearSRGBColorSpace,
  16001. //depthBuffer: false
  16002. };
  16003. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  16004. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  16005. if ( this._pingPongRenderTarget !== null ) {
  16006. this._dispose();
  16007. }
  16008. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  16009. const { _lodMax } = this;
  16010. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16011. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  16012. }
  16013. return cubeUVRenderTarget;
  16014. }
  16015. async _compileMaterial( material ) {
  16016. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16017. await this._renderer.compile( tmpMesh, _flatCamera );
  16018. }
  16019. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  16020. const cubeCamera = _cubeCamera;
  16021. cubeCamera.near = near;
  16022. cubeCamera.far = far;
  16023. // px, py, pz, nx, ny, nz
  16024. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  16025. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  16026. const renderer = this._renderer;
  16027. const originalAutoClear = renderer.autoClear;
  16028. renderer.getClearColor( _clearColor$2 );
  16029. renderer.autoClear = false;
  16030. let backgroundBox = this._backgroundBox;
  16031. if ( backgroundBox === null ) {
  16032. const backgroundMaterial = new MeshBasicMaterial( {
  16033. name: 'PMREM.Background',
  16034. side: BackSide,
  16035. depthWrite: false,
  16036. depthTest: false
  16037. } );
  16038. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16039. }
  16040. let useSolidColor = false;
  16041. const background = scene.background;
  16042. if ( background ) {
  16043. if ( background.isColor ) {
  16044. backgroundBox.material.color.copy( background );
  16045. scene.background = null;
  16046. useSolidColor = true;
  16047. }
  16048. } else {
  16049. backgroundBox.material.color.copy( _clearColor$2 );
  16050. useSolidColor = true;
  16051. }
  16052. renderer.setRenderTarget( cubeUVRenderTarget );
  16053. renderer.clear();
  16054. if ( useSolidColor ) {
  16055. renderer.render( backgroundBox, cubeCamera );
  16056. }
  16057. for ( let i = 0; i < 6; i ++ ) {
  16058. const col = i % 3;
  16059. if ( col === 0 ) {
  16060. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16061. cubeCamera.position.set( position.x, position.y, position.z );
  16062. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  16063. } else if ( col === 1 ) {
  16064. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16065. cubeCamera.position.set( position.x, position.y, position.z );
  16066. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  16067. } else {
  16068. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16069. cubeCamera.position.set( position.x, position.y, position.z );
  16070. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  16071. }
  16072. const size = this._cubeSize;
  16073. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16074. renderer.render( scene, cubeCamera );
  16075. }
  16076. renderer.autoClear = originalAutoClear;
  16077. scene.background = background;
  16078. }
  16079. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16080. const renderer = this._renderer;
  16081. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16082. if ( isCubeTexture ) {
  16083. if ( this._cubemapMaterial === null ) {
  16084. this._cubemapMaterial = _getCubemapMaterial( texture );
  16085. }
  16086. } else {
  16087. if ( this._equirectMaterial === null ) {
  16088. this._equirectMaterial = _getEquirectMaterial( texture );
  16089. }
  16090. }
  16091. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16092. material.fragmentNode.value = texture;
  16093. const mesh = this._lodMeshes[ 0 ];
  16094. mesh.material = material;
  16095. const size = this._cubeSize;
  16096. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16097. renderer.setRenderTarget( cubeUVRenderTarget );
  16098. renderer.render( mesh, _flatCamera );
  16099. }
  16100. _applyPMREM( cubeUVRenderTarget ) {
  16101. const renderer = this._renderer;
  16102. const autoClear = renderer.autoClear;
  16103. renderer.autoClear = false;
  16104. const n = this._lodPlanes.length;
  16105. for ( let i = 1; i < n; i ++ ) {
  16106. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16107. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16108. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16109. }
  16110. renderer.autoClear = autoClear;
  16111. }
  16112. /**
  16113. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16114. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16115. * the blur latitudinally (around the poles), and then longitudinally (towards
  16116. * the poles) to approximate the orthogonally-separable blur. It is least
  16117. * accurate at the poles, but still does a decent job.
  16118. *
  16119. * @private
  16120. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  16121. * @param {number} lodIn - The input level-of-detail.
  16122. * @param {number} lodOut - The output level-of-detail.
  16123. * @param {number} sigma - The blur radius in radians.
  16124. * @param {Vector3} [poleAxis] - The pole axis.
  16125. */
  16126. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16127. const pingPongRenderTarget = this._pingPongRenderTarget;
  16128. this._halfBlur(
  16129. cubeUVRenderTarget,
  16130. pingPongRenderTarget,
  16131. lodIn,
  16132. lodOut,
  16133. sigma,
  16134. 'latitudinal',
  16135. poleAxis );
  16136. this._halfBlur(
  16137. pingPongRenderTarget,
  16138. cubeUVRenderTarget,
  16139. lodOut,
  16140. lodOut,
  16141. sigma,
  16142. 'longitudinal',
  16143. poleAxis );
  16144. }
  16145. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16146. const renderer = this._renderer;
  16147. const blurMaterial = this._blurMaterial;
  16148. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16149. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16150. }
  16151. // Number of standard deviations at which to cut off the discrete approximation.
  16152. const STANDARD_DEVIATIONS = 3;
  16153. const blurMesh = this._lodMeshes[ lodOut ];
  16154. blurMesh.material = blurMaterial;
  16155. const blurUniforms = _uniformsMap.get( blurMaterial );
  16156. const pixels = this._sizeLods[ lodIn ] - 1;
  16157. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16158. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16159. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16160. if ( samples > MAX_SAMPLES ) {
  16161. console.warn( `sigmaRadians, ${
  16162. sigmaRadians}, is too large and will clip, as it requested ${
  16163. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16164. }
  16165. const weights = [];
  16166. let sum = 0;
  16167. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16168. const x = i / sigmaPixels;
  16169. const weight = Math.exp( - x * x / 2 );
  16170. weights.push( weight );
  16171. if ( i === 0 ) {
  16172. sum += weight;
  16173. } else if ( i < samples ) {
  16174. sum += 2 * weight;
  16175. }
  16176. }
  16177. for ( let i = 0; i < weights.length; i ++ ) {
  16178. weights[ i ] = weights[ i ] / sum;
  16179. }
  16180. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16181. blurUniforms.envMap.value = targetIn.texture;
  16182. blurUniforms.samples.value = samples;
  16183. blurUniforms.weights.array = weights;
  16184. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16185. if ( poleAxis ) {
  16186. blurUniforms.poleAxis.value = poleAxis;
  16187. }
  16188. const { _lodMax } = this;
  16189. blurUniforms.dTheta.value = radiansPerPixel;
  16190. blurUniforms.mipInt.value = _lodMax - lodIn;
  16191. const outputSize = this._sizeLods[ lodOut ];
  16192. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16193. const y = 4 * ( this._cubeSize - outputSize );
  16194. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16195. renderer.setRenderTarget( targetOut );
  16196. renderer.render( blurMesh, _flatCamera );
  16197. }
  16198. }
  16199. function _createPlanes( lodMax ) {
  16200. const lodPlanes = [];
  16201. const sizeLods = [];
  16202. const sigmas = [];
  16203. const lodMeshes = [];
  16204. let lod = lodMax;
  16205. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16206. for ( let i = 0; i < totalLods; i ++ ) {
  16207. const sizeLod = Math.pow( 2, lod );
  16208. sizeLods.push( sizeLod );
  16209. let sigma = 1.0 / sizeLod;
  16210. if ( i > lodMax - LOD_MIN ) {
  16211. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16212. } else if ( i === 0 ) {
  16213. sigma = 0;
  16214. }
  16215. sigmas.push( sigma );
  16216. const texelSize = 1.0 / ( sizeLod - 2 );
  16217. const min = - texelSize;
  16218. const max = 1 + texelSize;
  16219. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16220. const cubeFaces = 6;
  16221. const vertices = 6;
  16222. const positionSize = 3;
  16223. const uvSize = 2;
  16224. const faceIndexSize = 1;
  16225. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16226. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16227. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16228. for ( let face = 0; face < cubeFaces; face ++ ) {
  16229. const x = ( face % 3 ) * 2 / 3 - 1;
  16230. const y = face > 2 ? 0 : -1;
  16231. const coordinates = [
  16232. x, y, 0,
  16233. x + 2 / 3, y, 0,
  16234. x + 2 / 3, y + 1, 0,
  16235. x, y, 0,
  16236. x + 2 / 3, y + 1, 0,
  16237. x, y + 1, 0
  16238. ];
  16239. const faceIdx = _faceLib[ face ];
  16240. position.set( coordinates, positionSize * vertices * faceIdx );
  16241. uv.set( uv1, uvSize * vertices * faceIdx );
  16242. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16243. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16244. }
  16245. const planes = new BufferGeometry();
  16246. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16247. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16248. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  16249. lodPlanes.push( planes );
  16250. lodMeshes.push( new Mesh( planes, null ) );
  16251. if ( lod > LOD_MIN ) {
  16252. lod --;
  16253. }
  16254. }
  16255. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  16256. }
  16257. function _createRenderTarget( width, height, params ) {
  16258. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  16259. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  16260. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  16261. cubeUVRenderTarget.texture.isPMREMTexture = true;
  16262. cubeUVRenderTarget.scissorTest = true;
  16263. return cubeUVRenderTarget;
  16264. }
  16265. function _setViewport( target, x, y, width, height ) {
  16266. target.viewport.set( x, y, width, height );
  16267. target.scissor.set( x, y, width, height );
  16268. }
  16269. function _getMaterial( type ) {
  16270. const material = new NodeMaterial();
  16271. material.depthTest = false;
  16272. material.depthWrite = false;
  16273. material.blending = NoBlending;
  16274. material.name = `PMREM_${ type }`;
  16275. return material;
  16276. }
  16277. function _getBlurShader( lodMax, width, height ) {
  16278. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  16279. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  16280. const dTheta = uniform( 0 );
  16281. const n = float( MAX_SAMPLES );
  16282. const latitudinal = uniform( 0 ); // false, bool
  16283. const samples = uniform( 1 ); // int
  16284. const envMap = texture( null );
  16285. const mipInt = uniform( 0 ); // int
  16286. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  16287. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  16288. const CUBEUV_MAX_MIP = float( lodMax );
  16289. const materialUniforms = {
  16290. n,
  16291. latitudinal,
  16292. weights,
  16293. poleAxis,
  16294. outputDirection: _outputDirection,
  16295. dTheta,
  16296. samples,
  16297. envMap,
  16298. mipInt,
  16299. CUBEUV_TEXEL_WIDTH,
  16300. CUBEUV_TEXEL_HEIGHT,
  16301. CUBEUV_MAX_MIP
  16302. };
  16303. const material = _getMaterial( 'blur' );
  16304. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  16305. _uniformsMap.set( material, materialUniforms );
  16306. return material;
  16307. }
  16308. function _getCubemapMaterial( envTexture ) {
  16309. const material = _getMaterial( 'cubemap' );
  16310. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  16311. return material;
  16312. }
  16313. function _getEquirectMaterial( envTexture ) {
  16314. const material = _getMaterial( 'equirect' );
  16315. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  16316. return material;
  16317. }
  16318. const _cache = new WeakMap();
  16319. /**
  16320. * Generates the cubeUV size based on the given image height.
  16321. *
  16322. * @private
  16323. * @param {number} imageHeight - The image height.
  16324. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  16325. */
  16326. function _generateCubeUVSize( imageHeight ) {
  16327. const maxMip = Math.log2( imageHeight ) - 2;
  16328. const texelHeight = 1.0 / imageHeight;
  16329. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  16330. return { texelWidth, texelHeight, maxMip };
  16331. }
  16332. /**
  16333. * Generates a PMREM from the given texture.
  16334. *
  16335. * @private
  16336. * @param {Texture} texture - The texture to create the PMREM for.
  16337. * @param {Renderer} renderer - The renderer.
  16338. * @param {PMREMGenerator} generator - The PMREM generator.
  16339. * @return {?Texture} The PMREM.
  16340. */
  16341. function _getPMREMFromTexture( texture, renderer, generator ) {
  16342. const cache = _getCache( renderer );
  16343. let cacheTexture = cache.get( texture );
  16344. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  16345. if ( pmremVersion !== texture.pmremVersion ) {
  16346. const image = texture.image;
  16347. if ( texture.isCubeTexture ) {
  16348. if ( isCubeMapReady( image ) ) {
  16349. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  16350. } else {
  16351. return null;
  16352. }
  16353. } else {
  16354. if ( isEquirectangularMapReady( image ) ) {
  16355. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  16356. } else {
  16357. return null;
  16358. }
  16359. }
  16360. cacheTexture.pmremVersion = texture.pmremVersion;
  16361. cache.set( texture, cacheTexture );
  16362. }
  16363. return cacheTexture.texture;
  16364. }
  16365. /**
  16366. * Returns a cache that stores generated PMREMs for the respective textures.
  16367. * A cache must be maintained per renderer since PMREMs are render target textures
  16368. * which can't be shared across render contexts.
  16369. *
  16370. * @private
  16371. * @param {Renderer} renderer - The renderer.
  16372. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  16373. */
  16374. function _getCache( renderer ) {
  16375. let rendererCache = _cache.get( renderer );
  16376. if ( rendererCache === undefined ) {
  16377. rendererCache = new WeakMap();
  16378. _cache.set( renderer, rendererCache );
  16379. }
  16380. return rendererCache;
  16381. }
  16382. /**
  16383. * This node represents a PMREM which is a special type of preprocessed
  16384. * environment map intended for PBR materials.
  16385. *
  16386. * ```js
  16387. * const material = new MeshStandardNodeMaterial();
  16388. * material.envNode = pmremTexture( envMap );
  16389. * ```
  16390. *
  16391. * @augments TempNode
  16392. */
  16393. class PMREMNode extends TempNode {
  16394. static get type() {
  16395. return 'PMREMNode';
  16396. }
  16397. /**
  16398. * Constructs a new function overloading node.
  16399. *
  16400. * @param {Texture} value - The input texture.
  16401. * @param {Node<vec2>} [uvNode=null] - The uv node.
  16402. * @param {Node<float>} [levelNode=null] - The level node.
  16403. */
  16404. constructor( value, uvNode = null, levelNode = null ) {
  16405. super( 'vec3' );
  16406. /**
  16407. * Reference to the input texture.
  16408. *
  16409. * @private
  16410. * @type {Texture}
  16411. */
  16412. this._value = value;
  16413. /**
  16414. * Reference to the generated PMREM.
  16415. *
  16416. * @private
  16417. * @type {Texture | null}
  16418. * @default null
  16419. */
  16420. this._pmrem = null;
  16421. /**
  16422. * The uv node.
  16423. *
  16424. * @type {Node<vec2>}
  16425. */
  16426. this.uvNode = uvNode;
  16427. /**
  16428. * The level node.
  16429. *
  16430. * @type {Node<float>}
  16431. */
  16432. this.levelNode = levelNode;
  16433. /**
  16434. * Reference to a PMREM generator.
  16435. *
  16436. * @private
  16437. * @type {?PMREMGenerator}
  16438. * @default null
  16439. */
  16440. this._generator = null;
  16441. const defaultTexture = new Texture();
  16442. defaultTexture.isRenderTargetTexture = true;
  16443. /**
  16444. * The texture node holding the generated PMREM.
  16445. *
  16446. * @private
  16447. * @type {TextureNode}
  16448. */
  16449. this._texture = texture( defaultTexture );
  16450. /**
  16451. * A uniform representing the PMREM's width.
  16452. *
  16453. * @private
  16454. * @type {UniformNode<float>}
  16455. */
  16456. this._width = uniform( 0 );
  16457. /**
  16458. * A uniform representing the PMREM's height.
  16459. *
  16460. * @private
  16461. * @type {UniformNode<float>}
  16462. */
  16463. this._height = uniform( 0 );
  16464. /**
  16465. * A uniform representing the PMREM's max Mip.
  16466. *
  16467. * @private
  16468. * @type {UniformNode<float>}
  16469. */
  16470. this._maxMip = uniform( 0 );
  16471. /**
  16472. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  16473. *
  16474. * @type {string}
  16475. * @default 'render'
  16476. */
  16477. this.updateBeforeType = NodeUpdateType.RENDER;
  16478. }
  16479. set value( value ) {
  16480. this._value = value;
  16481. this._pmrem = null;
  16482. }
  16483. /**
  16484. * The node's texture value.
  16485. *
  16486. * @type {Texture}
  16487. */
  16488. get value() {
  16489. return this._value;
  16490. }
  16491. /**
  16492. * Uses the given PMREM texture to update internal values.
  16493. *
  16494. * @param {Texture} texture - The PMREM texture.
  16495. */
  16496. updateFromTexture( texture ) {
  16497. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  16498. this._texture.value = texture;
  16499. this._width.value = cubeUVSize.texelWidth;
  16500. this._height.value = cubeUVSize.texelHeight;
  16501. this._maxMip.value = cubeUVSize.maxMip;
  16502. }
  16503. updateBefore( frame ) {
  16504. let pmrem = this._pmrem;
  16505. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  16506. const texture = this._value;
  16507. if ( pmremVersion !== texture.pmremVersion ) {
  16508. if ( texture.isPMREMTexture === true ) {
  16509. pmrem = texture;
  16510. } else {
  16511. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  16512. }
  16513. if ( pmrem !== null ) {
  16514. this._pmrem = pmrem;
  16515. this.updateFromTexture( pmrem );
  16516. }
  16517. }
  16518. }
  16519. setup( builder ) {
  16520. if ( this._generator === null ) {
  16521. this._generator = new PMREMGenerator( builder.renderer );
  16522. }
  16523. this.updateBefore( builder );
  16524. //
  16525. let uvNode = this.uvNode;
  16526. if ( uvNode === null && builder.context.getUV ) {
  16527. uvNode = builder.context.getUV( this );
  16528. }
  16529. //
  16530. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  16531. //
  16532. let levelNode = this.levelNode;
  16533. if ( levelNode === null && builder.context.getTextureLevel ) {
  16534. levelNode = builder.context.getTextureLevel( this );
  16535. }
  16536. //
  16537. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  16538. }
  16539. dispose() {
  16540. super.dispose();
  16541. if ( this._generator !== null ) this._generator.dispose();
  16542. }
  16543. }
  16544. /**
  16545. * Returns `true` if the given cube map image has been fully loaded.
  16546. *
  16547. * @private
  16548. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  16549. * @return {boolean} Whether the given cube map is ready or not.
  16550. */
  16551. function isCubeMapReady( image ) {
  16552. if ( image === null || image === undefined ) return false;
  16553. let count = 0;
  16554. const length = 6;
  16555. for ( let i = 0; i < length; i ++ ) {
  16556. if ( image[ i ] !== undefined ) count ++;
  16557. }
  16558. return count === length;
  16559. }
  16560. /**
  16561. * Returns `true` if the given equirectangular image has been fully loaded.
  16562. *
  16563. * @private
  16564. * @param {(Image|Object)} image - The equirectangular image.
  16565. * @return {boolean} Whether the given cube map is ready or not.
  16566. */
  16567. function isEquirectangularMapReady( image ) {
  16568. if ( image === null || image === undefined ) return false;
  16569. return image.height > 0;
  16570. }
  16571. /**
  16572. * TSL function for creating a PMREM node.
  16573. *
  16574. * @tsl
  16575. * @function
  16576. * @param {Texture} value - The input texture.
  16577. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  16578. * @param {?Node<float>} [levelNode=null] - The level node.
  16579. * @returns {PMREMNode}
  16580. */
  16581. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  16582. const _envNodeCache = new WeakMap();
  16583. /**
  16584. * Represents a physical model for Image-based lighting (IBL). The environment
  16585. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  16586. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  16587. *
  16588. * @augments LightingNode
  16589. */
  16590. class EnvironmentNode extends LightingNode {
  16591. static get type() {
  16592. return 'EnvironmentNode';
  16593. }
  16594. /**
  16595. * Constructs a new environment node.
  16596. *
  16597. * @param {Node} [envNode=null] - A node representing the environment.
  16598. */
  16599. constructor( envNode = null ) {
  16600. super();
  16601. /**
  16602. * A node representing the environment.
  16603. *
  16604. * @type {?Node}
  16605. * @default null
  16606. */
  16607. this.envNode = envNode;
  16608. }
  16609. setup( builder ) {
  16610. const { material } = builder;
  16611. let envNode = this.envNode;
  16612. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  16613. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  16614. let cacheEnvNode = _envNodeCache.get( value );
  16615. if ( cacheEnvNode === undefined ) {
  16616. cacheEnvNode = pmremTexture( value );
  16617. _envNodeCache.set( value, cacheEnvNode );
  16618. }
  16619. envNode = cacheEnvNode;
  16620. }
  16621. //
  16622. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  16623. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  16624. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  16625. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  16626. const isolateRadiance = cache( radiance );
  16627. const isolateIrradiance = cache( irradiance );
  16628. //
  16629. builder.context.radiance.addAssign( isolateRadiance );
  16630. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  16631. //
  16632. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  16633. if ( clearcoatRadiance ) {
  16634. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( materialEnvIntensity );
  16635. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  16636. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  16637. }
  16638. }
  16639. }
  16640. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  16641. let reflectVec = null;
  16642. return {
  16643. getUV: () => {
  16644. if ( reflectVec === null ) {
  16645. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  16646. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  16647. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  16648. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  16649. }
  16650. return reflectVec;
  16651. },
  16652. getTextureLevel: () => {
  16653. return roughnessNode;
  16654. }
  16655. };
  16656. };
  16657. const createIrradianceContext = ( normalWorldNode ) => {
  16658. return {
  16659. getUV: () => {
  16660. return normalWorldNode;
  16661. },
  16662. getTextureLevel: () => {
  16663. return float( 1.0 );
  16664. }
  16665. };
  16666. };
  16667. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  16668. /**
  16669. * Node material version of {@link MeshStandardMaterial}.
  16670. *
  16671. * @augments NodeMaterial
  16672. */
  16673. class MeshStandardNodeMaterial extends NodeMaterial {
  16674. static get type() {
  16675. return 'MeshStandardNodeMaterial';
  16676. }
  16677. /**
  16678. * Constructs a new mesh standard node material.
  16679. *
  16680. * @param {Object} [parameters] - The configuration parameter.
  16681. */
  16682. constructor( parameters ) {
  16683. super();
  16684. /**
  16685. * This flag can be used for type testing.
  16686. *
  16687. * @type {boolean}
  16688. * @readonly
  16689. * @default true
  16690. */
  16691. this.isMeshStandardNodeMaterial = true;
  16692. /**
  16693. * Set to `true` because standard materials react on lights.
  16694. *
  16695. * @type {boolean}
  16696. * @default true
  16697. */
  16698. this.lights = true;
  16699. /**
  16700. * The emissive color of standard materials is by default inferred from the `emissive`,
  16701. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  16702. * overwrite the default and define the emissive color with a node instead.
  16703. *
  16704. * If you don't want to overwrite the emissive color but modify the existing
  16705. * value instead, use {@link materialEmissive}.
  16706. *
  16707. * @type {?Node<vec3>}
  16708. * @default null
  16709. */
  16710. this.emissiveNode = null;
  16711. /**
  16712. * The metalness of standard materials is by default inferred from the `metalness`,
  16713. * and `metalnessMap` properties. This node property allows to
  16714. * overwrite the default and define the metalness with a node instead.
  16715. *
  16716. * If you don't want to overwrite the metalness but modify the existing
  16717. * value instead, use {@link materialMetalness}.
  16718. *
  16719. * @type {?Node<float>}
  16720. * @default null
  16721. */
  16722. this.metalnessNode = null;
  16723. /**
  16724. * The roughness of standard materials is by default inferred from the `roughness`,
  16725. * and `roughnessMap` properties. This node property allows to
  16726. * overwrite the default and define the roughness with a node instead.
  16727. *
  16728. * If you don't want to overwrite the roughness but modify the existing
  16729. * value instead, use {@link materialRoughness}.
  16730. *
  16731. * @type {?Node<float>}
  16732. * @default null
  16733. */
  16734. this.roughnessNode = null;
  16735. this.setDefaultValues( _defaultValues$6 );
  16736. this.setValues( parameters );
  16737. }
  16738. /**
  16739. * Overwritten since this type of material uses {@link EnvironmentNode}
  16740. * to implement the PBR (PMREM based) environment mapping. Besides, the
  16741. * method honors `Scene.environment`.
  16742. *
  16743. * @param {NodeBuilder} builder - The current node builder.
  16744. * @return {?EnvironmentNode<vec3>} The environment node.
  16745. */
  16746. setupEnvironment( builder ) {
  16747. let envNode = super.setupEnvironment( builder );
  16748. if ( envNode === null && builder.environmentNode ) {
  16749. envNode = builder.environmentNode;
  16750. }
  16751. return envNode ? new EnvironmentNode( envNode ) : null;
  16752. }
  16753. /**
  16754. * Setups the lighting model.
  16755. *
  16756. * @return {PhysicalLightingModel} The lighting model.
  16757. */
  16758. setupLightingModel( /*builder*/ ) {
  16759. return new PhysicalLightingModel();
  16760. }
  16761. /**
  16762. * Setups the specular related node variables.
  16763. */
  16764. setupSpecular() {
  16765. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  16766. specularColor.assign( specularColorNode );
  16767. specularF90.assign( 1.0 );
  16768. }
  16769. /**
  16770. * Setups the standard specific node variables.
  16771. *
  16772. * @param {NodeBuilder} builder - The current node builder.
  16773. */
  16774. setupVariants() {
  16775. // METALNESS
  16776. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  16777. metalness.assign( metalnessNode );
  16778. // ROUGHNESS
  16779. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  16780. roughnessNode = getRoughness( { roughness: roughnessNode } );
  16781. roughness.assign( roughnessNode );
  16782. // SPECULAR COLOR
  16783. this.setupSpecular();
  16784. // DIFFUSE COLOR
  16785. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  16786. }
  16787. copy( source ) {
  16788. this.emissiveNode = source.emissiveNode;
  16789. this.metalnessNode = source.metalnessNode;
  16790. this.roughnessNode = source.roughnessNode;
  16791. return super.copy( source );
  16792. }
  16793. }
  16794. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  16795. /**
  16796. * Node material version of {@link MeshPhysicalMaterial}.
  16797. *
  16798. * @augments MeshStandardNodeMaterial
  16799. */
  16800. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  16801. static get type() {
  16802. return 'MeshPhysicalNodeMaterial';
  16803. }
  16804. /**
  16805. * Constructs a new mesh physical node material.
  16806. *
  16807. * @param {Object} [parameters] - The configuration parameter.
  16808. */
  16809. constructor( parameters ) {
  16810. super();
  16811. /**
  16812. * This flag can be used for type testing.
  16813. *
  16814. * @type {boolean}
  16815. * @readonly
  16816. * @default true
  16817. */
  16818. this.isMeshPhysicalNodeMaterial = true;
  16819. /**
  16820. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  16821. * and `clearcoatMap` properties. This node property allows to overwrite the default
  16822. * and define the clearcoat with a node instead.
  16823. *
  16824. * If you don't want to overwrite the clearcoat but modify the existing
  16825. * value instead, use {@link materialClearcoat}.
  16826. *
  16827. * @type {?Node<float>}
  16828. * @default null
  16829. */
  16830. this.clearcoatNode = null;
  16831. /**
  16832. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  16833. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  16834. * and define the clearcoat roughness with a node instead.
  16835. *
  16836. * If you don't want to overwrite the clearcoat roughness but modify the existing
  16837. * value instead, use {@link materialClearcoatRoughness}.
  16838. *
  16839. * @type {?Node<float>}
  16840. * @default null
  16841. */
  16842. this.clearcoatRoughnessNode = null;
  16843. /**
  16844. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  16845. * property. This node property allows to overwrite the default
  16846. * and define the clearcoat normal with a node instead.
  16847. *
  16848. * If you don't want to overwrite the clearcoat normal but modify the existing
  16849. * value instead, use {@link materialClearcoatNormal}.
  16850. *
  16851. * @type {?Node<vec3>}
  16852. * @default null
  16853. */
  16854. this.clearcoatNormalNode = null;
  16855. /**
  16856. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  16857. * and `sheenColorMap` properties. This node property allows to overwrite the default
  16858. * and define the sheen with a node instead.
  16859. *
  16860. * If you don't want to overwrite the sheen but modify the existing
  16861. * value instead, use {@link materialSheen}.
  16862. *
  16863. * @type {?Node<vec3>}
  16864. * @default null
  16865. */
  16866. this.sheenNode = null;
  16867. /**
  16868. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  16869. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  16870. * and define the sheen roughness with a node instead.
  16871. *
  16872. * If you don't want to overwrite the sheen roughness but modify the existing
  16873. * value instead, use {@link materialSheenRoughness}.
  16874. *
  16875. * @type {?Node<float>}
  16876. * @default null
  16877. */
  16878. this.sheenRoughnessNode = null;
  16879. /**
  16880. * The iridescence of physical materials is by default inferred from the `iridescence`
  16881. * property. This node property allows to overwrite the default
  16882. * and define the iridescence with a node instead.
  16883. *
  16884. * If you don't want to overwrite the iridescence but modify the existing
  16885. * value instead, use {@link materialIridescence}.
  16886. *
  16887. * @type {?Node<float>}
  16888. * @default null
  16889. */
  16890. this.iridescenceNode = null;
  16891. /**
  16892. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  16893. * property. This node property allows to overwrite the default
  16894. * and define the iridescence IOR with a node instead.
  16895. *
  16896. * If you don't want to overwrite the iridescence IOR but modify the existing
  16897. * value instead, use {@link materialIridescenceIOR}.
  16898. *
  16899. * @type {?Node<float>}
  16900. * @default null
  16901. */
  16902. this.iridescenceIORNode = null;
  16903. /**
  16904. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  16905. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  16906. * and define the iridescence thickness with a node instead.
  16907. *
  16908. * If you don't want to overwrite the iridescence thickness but modify the existing
  16909. * value instead, use {@link materialIridescenceThickness}.
  16910. *
  16911. * @type {?Node<float>}
  16912. * @default null
  16913. */
  16914. this.iridescenceThicknessNode = null;
  16915. /**
  16916. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  16917. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  16918. * and define the specular intensity with a node instead.
  16919. *
  16920. * If you don't want to overwrite the specular intensity but modify the existing
  16921. * value instead, use {@link materialSpecularIntensity}.
  16922. *
  16923. * @type {?Node<float>}
  16924. * @default null
  16925. */
  16926. this.specularIntensityNode = null;
  16927. /**
  16928. * The specular color of physical materials is by default inferred from the `specularColor`
  16929. * and `specularColorMap` properties. This node property allows to overwrite the default
  16930. * and define the specular color with a node instead.
  16931. *
  16932. * If you don't want to overwrite the specular color but modify the existing
  16933. * value instead, use {@link materialSpecularColor}.
  16934. *
  16935. * @type {?Node<vec3>}
  16936. * @default null
  16937. */
  16938. this.specularColorNode = null;
  16939. /**
  16940. * The ior of physical materials is by default inferred from the `ior`
  16941. * property. This node property allows to overwrite the default
  16942. * and define the ior with a node instead.
  16943. *
  16944. * If you don't want to overwrite the ior but modify the existing
  16945. * value instead, use {@link materialIOR}.
  16946. *
  16947. * @type {?Node<float>}
  16948. * @default null
  16949. */
  16950. this.iorNode = null;
  16951. /**
  16952. * The transmission of physical materials is by default inferred from the `transmission` and
  16953. * `transmissionMap` properties. This node property allows to overwrite the default
  16954. * and define the transmission with a node instead.
  16955. *
  16956. * If you don't want to overwrite the transmission but modify the existing
  16957. * value instead, use {@link materialTransmission}.
  16958. *
  16959. * @type {?Node<float>}
  16960. * @default null
  16961. */
  16962. this.transmissionNode = null;
  16963. /**
  16964. * The thickness of physical materials is by default inferred from the `thickness` and
  16965. * `thicknessMap` properties. This node property allows to overwrite the default
  16966. * and define the thickness with a node instead.
  16967. *
  16968. * If you don't want to overwrite the thickness but modify the existing
  16969. * value instead, use {@link materialThickness}.
  16970. *
  16971. * @type {?Node<float>}
  16972. * @default null
  16973. */
  16974. this.thicknessNode = null;
  16975. /**
  16976. * The attenuation distance of physical materials is by default inferred from the
  16977. * `attenuationDistance` property. This node property allows to overwrite the default
  16978. * and define the attenuation distance with a node instead.
  16979. *
  16980. * If you don't want to overwrite the attenuation distance but modify the existing
  16981. * value instead, use {@link materialAttenuationDistance}.
  16982. *
  16983. * @type {?Node<float>}
  16984. * @default null
  16985. */
  16986. this.attenuationDistanceNode = null;
  16987. /**
  16988. * The attenuation color of physical materials is by default inferred from the
  16989. * `attenuationColor` property. This node property allows to overwrite the default
  16990. * and define the attenuation color with a node instead.
  16991. *
  16992. * If you don't want to overwrite the attenuation color but modify the existing
  16993. * value instead, use {@link materialAttenuationColor}.
  16994. *
  16995. * @type {?Node<vec3>}
  16996. * @default null
  16997. */
  16998. this.attenuationColorNode = null;
  16999. /**
  17000. * The dispersion of physical materials is by default inferred from the
  17001. * `dispersion` property. This node property allows to overwrite the default
  17002. * and define the dispersion with a node instead.
  17003. *
  17004. * If you don't want to overwrite the dispersion but modify the existing
  17005. * value instead, use {@link materialDispersion}.
  17006. *
  17007. * @type {?Node<float>}
  17008. * @default null
  17009. */
  17010. this.dispersionNode = null;
  17011. /**
  17012. * The anisotropy of physical materials is by default inferred from the
  17013. * `anisotropy` property. This node property allows to overwrite the default
  17014. * and define the anisotropy with a node instead.
  17015. *
  17016. * If you don't want to overwrite the anisotropy but modify the existing
  17017. * value instead, use {@link materialAnisotropy}.
  17018. *
  17019. * @type {?Node<float>}
  17020. * @default null
  17021. */
  17022. this.anisotropyNode = null;
  17023. this.setDefaultValues( _defaultValues$5 );
  17024. this.setValues( parameters );
  17025. }
  17026. /**
  17027. * Whether the lighting model should use clearcoat or not.
  17028. *
  17029. * @type {boolean}
  17030. * @default true
  17031. */
  17032. get useClearcoat() {
  17033. return this.clearcoat > 0 || this.clearcoatNode !== null;
  17034. }
  17035. /**
  17036. * Whether the lighting model should use iridescence or not.
  17037. *
  17038. * @type {boolean}
  17039. * @default true
  17040. */
  17041. get useIridescence() {
  17042. return this.iridescence > 0 || this.iridescenceNode !== null;
  17043. }
  17044. /**
  17045. * Whether the lighting model should use sheen or not.
  17046. *
  17047. * @type {boolean}
  17048. * @default true
  17049. */
  17050. get useSheen() {
  17051. return this.sheen > 0 || this.sheenNode !== null;
  17052. }
  17053. /**
  17054. * Whether the lighting model should use anisotropy or not.
  17055. *
  17056. * @type {boolean}
  17057. * @default true
  17058. */
  17059. get useAnisotropy() {
  17060. return this.anisotropy > 0 || this.anisotropyNode !== null;
  17061. }
  17062. /**
  17063. * Whether the lighting model should use transmission or not.
  17064. *
  17065. * @type {boolean}
  17066. * @default true
  17067. */
  17068. get useTransmission() {
  17069. return this.transmission > 0 || this.transmissionNode !== null;
  17070. }
  17071. /**
  17072. * Whether the lighting model should use dispersion or not.
  17073. *
  17074. * @type {boolean}
  17075. * @default true
  17076. */
  17077. get useDispersion() {
  17078. return this.dispersion > 0 || this.dispersionNode !== null;
  17079. }
  17080. /**
  17081. * Setups the specular related node variables.
  17082. */
  17083. setupSpecular() {
  17084. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  17085. ior.assign( iorNode );
  17086. 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 ) );
  17087. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  17088. }
  17089. /**
  17090. * Setups the lighting model.
  17091. *
  17092. * @return {PhysicalLightingModel} The lighting model.
  17093. */
  17094. setupLightingModel( /*builder*/ ) {
  17095. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  17096. }
  17097. /**
  17098. * Setups the physical specific node variables.
  17099. *
  17100. * @param {NodeBuilder} builder - The current node builder.
  17101. */
  17102. setupVariants( builder ) {
  17103. super.setupVariants( builder );
  17104. // CLEARCOAT
  17105. if ( this.useClearcoat ) {
  17106. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  17107. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  17108. clearcoat.assign( clearcoatNode );
  17109. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  17110. }
  17111. // SHEEN
  17112. if ( this.useSheen ) {
  17113. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  17114. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  17115. sheen.assign( sheenNode );
  17116. sheenRoughness.assign( sheenRoughnessNode );
  17117. }
  17118. // IRIDESCENCE
  17119. if ( this.useIridescence ) {
  17120. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  17121. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  17122. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  17123. iridescence.assign( iridescenceNode );
  17124. iridescenceIOR.assign( iridescenceIORNode );
  17125. iridescenceThickness.assign( iridescenceThicknessNode );
  17126. }
  17127. // ANISOTROPY
  17128. if ( this.useAnisotropy ) {
  17129. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  17130. anisotropy.assign( anisotropyV.length() );
  17131. If( anisotropy.equal( 0.0 ), () => {
  17132. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  17133. } ).Else( () => {
  17134. anisotropyV.divAssign( vec2( anisotropy ) );
  17135. anisotropy.assign( anisotropy.saturate() );
  17136. } );
  17137. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  17138. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  17139. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  17140. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  17141. }
  17142. // TRANSMISSION
  17143. if ( this.useTransmission ) {
  17144. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  17145. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  17146. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  17147. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  17148. transmission.assign( transmissionNode );
  17149. thickness.assign( thicknessNode );
  17150. attenuationDistance.assign( attenuationDistanceNode );
  17151. attenuationColor.assign( attenuationColorNode );
  17152. if ( this.useDispersion ) {
  17153. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  17154. dispersion.assign( dispersionNode );
  17155. }
  17156. }
  17157. }
  17158. /**
  17159. * Setups the clearcoat normal node.
  17160. *
  17161. * @return {Node<vec3>} The clearcoat normal.
  17162. */
  17163. setupClearcoatNormal() {
  17164. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  17165. }
  17166. setup( builder ) {
  17167. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  17168. super.setup( builder );
  17169. }
  17170. copy( source ) {
  17171. this.clearcoatNode = source.clearcoatNode;
  17172. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  17173. this.clearcoatNormalNode = source.clearcoatNormalNode;
  17174. this.sheenNode = source.sheenNode;
  17175. this.sheenRoughnessNode = source.sheenRoughnessNode;
  17176. this.iridescenceNode = source.iridescenceNode;
  17177. this.iridescenceIORNode = source.iridescenceIORNode;
  17178. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  17179. this.specularIntensityNode = source.specularIntensityNode;
  17180. this.specularColorNode = source.specularColorNode;
  17181. this.transmissionNode = source.transmissionNode;
  17182. this.thicknessNode = source.thicknessNode;
  17183. this.attenuationDistanceNode = source.attenuationDistanceNode;
  17184. this.attenuationColorNode = source.attenuationColorNode;
  17185. this.dispersionNode = source.dispersionNode;
  17186. this.anisotropyNode = source.anisotropyNode;
  17187. return super.copy( source );
  17188. }
  17189. }
  17190. /**
  17191. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  17192. *
  17193. * @augments PhysicalLightingModel
  17194. */
  17195. class SSSLightingModel extends PhysicalLightingModel {
  17196. /**
  17197. * Constructs a new physical lighting model.
  17198. *
  17199. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17200. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17201. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17202. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17203. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17204. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17205. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  17206. */
  17207. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  17208. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  17209. /**
  17210. * Whether the lighting model should use SSS or not.
  17211. *
  17212. * @type {boolean}
  17213. * @default false
  17214. */
  17215. this.useSSS = sss;
  17216. }
  17217. /**
  17218. * Extends the default implementation with a SSS term.
  17219. *
  17220. * 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/}
  17221. *
  17222. * @param {Object} input - The input data.
  17223. * @param {NodeBuilder} builder - The current node builder.
  17224. */
  17225. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17226. if ( this.useSSS === true ) {
  17227. const material = builder.material;
  17228. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  17229. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  17230. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  17231. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  17232. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  17233. }
  17234. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  17235. }
  17236. }
  17237. /**
  17238. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  17239. * that implements a Subsurface scattering (SSS) term.
  17240. *
  17241. * @augments MeshPhysicalNodeMaterial
  17242. */
  17243. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  17244. static get type() {
  17245. return 'MeshSSSNodeMaterial';
  17246. }
  17247. /**
  17248. * Constructs a new mesh SSS node material.
  17249. *
  17250. * @param {Object} [parameters] - The configuration parameter.
  17251. */
  17252. constructor( parameters ) {
  17253. super( parameters );
  17254. /**
  17255. * Represents the thickness color.
  17256. *
  17257. * @type {?Node<vec3>}
  17258. * @default null
  17259. */
  17260. this.thicknessColorNode = null;
  17261. /**
  17262. * Represents the distortion factor.
  17263. *
  17264. * @type {?Node<float>}
  17265. */
  17266. this.thicknessDistortionNode = float( 0.1 );
  17267. /**
  17268. * Represents the thickness ambient factor.
  17269. *
  17270. * @type {?Node<float>}
  17271. */
  17272. this.thicknessAmbientNode = float( 0.0 );
  17273. /**
  17274. * Represents the thickness attenuation.
  17275. *
  17276. * @type {?Node<float>}
  17277. */
  17278. this.thicknessAttenuationNode = float( .1 );
  17279. /**
  17280. * Represents the thickness power.
  17281. *
  17282. * @type {?Node<float>}
  17283. */
  17284. this.thicknessPowerNode = float( 2.0 );
  17285. /**
  17286. * Represents the thickness scale.
  17287. *
  17288. * @type {?Node<float>}
  17289. */
  17290. this.thicknessScaleNode = float( 10.0 );
  17291. }
  17292. /**
  17293. * Whether the lighting model should use SSS or not.
  17294. *
  17295. * @type {boolean}
  17296. * @default true
  17297. */
  17298. get useSSS() {
  17299. return this.thicknessColorNode !== null;
  17300. }
  17301. /**
  17302. * Setups the lighting model.
  17303. *
  17304. * @return {SSSLightingModel} The lighting model.
  17305. */
  17306. setupLightingModel( /*builder*/ ) {
  17307. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  17308. }
  17309. copy( source ) {
  17310. this.thicknessColorNode = source.thicknessColorNode;
  17311. this.thicknessDistortionNode = source.thicknessDistortionNode;
  17312. this.thicknessAmbientNode = source.thicknessAmbientNode;
  17313. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  17314. this.thicknessPowerNode = source.thicknessPowerNode;
  17315. this.thicknessScaleNode = source.thicknessScaleNode;
  17316. return super.copy( source );
  17317. }
  17318. }
  17319. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  17320. // dotNL will be from -1.0 to 1.0
  17321. const dotNL = normal.dot( lightDirection );
  17322. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  17323. if ( builder.material.gradientMap ) {
  17324. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  17325. return vec3( gradientMap.r );
  17326. } else {
  17327. const fw = coord.fwidth().mul( 0.5 );
  17328. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  17329. }
  17330. } );
  17331. /**
  17332. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  17333. *
  17334. * @augments LightingModel
  17335. */
  17336. class ToonLightingModel extends LightingModel {
  17337. /**
  17338. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  17339. * reduced to a small number of discrete shades to create a comic-like, flat look.
  17340. *
  17341. * @param {Object} lightData - The light data.
  17342. * @param {NodeBuilder} builder - The current node builder.
  17343. */
  17344. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17345. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  17346. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  17347. }
  17348. /**
  17349. * Implements the indirect lighting.
  17350. *
  17351. * @param {NodeBuilder} builder - The current node builder.
  17352. */
  17353. indirect( builder ) {
  17354. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  17355. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  17356. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17357. }
  17358. }
  17359. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  17360. /**
  17361. * Node material version of {@link MeshToonMaterial}.
  17362. *
  17363. * @augments NodeMaterial
  17364. */
  17365. class MeshToonNodeMaterial extends NodeMaterial {
  17366. static get type() {
  17367. return 'MeshToonNodeMaterial';
  17368. }
  17369. /**
  17370. * Constructs a new mesh toon node material.
  17371. *
  17372. * @param {Object} [parameters] - The configuration parameter.
  17373. */
  17374. constructor( parameters ) {
  17375. super();
  17376. /**
  17377. * This flag can be used for type testing.
  17378. *
  17379. * @type {boolean}
  17380. * @readonly
  17381. * @default true
  17382. */
  17383. this.isMeshToonNodeMaterial = true;
  17384. /**
  17385. * Set to `true` because toon materials react on lights.
  17386. *
  17387. * @type {boolean}
  17388. * @default true
  17389. */
  17390. this.lights = true;
  17391. this.setDefaultValues( _defaultValues$4 );
  17392. this.setValues( parameters );
  17393. }
  17394. /**
  17395. * Setups the lighting model.
  17396. *
  17397. * @return {ToonLightingModel} The lighting model.
  17398. */
  17399. setupLightingModel( /*builder*/ ) {
  17400. return new ToonLightingModel();
  17401. }
  17402. }
  17403. /**
  17404. * Can be used to compute texture coordinates for projecting a
  17405. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  17406. *
  17407. * @augments TempNode
  17408. */
  17409. class MatcapUVNode extends TempNode {
  17410. static get type() {
  17411. return 'MatcapUVNode';
  17412. }
  17413. /**
  17414. * Constructs a new matcap uv node.
  17415. */
  17416. constructor() {
  17417. super( 'vec2' );
  17418. }
  17419. setup() {
  17420. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  17421. const y = positionViewDirection.cross( x );
  17422. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  17423. }
  17424. }
  17425. /**
  17426. * TSL function for creating a matcap uv node.
  17427. *
  17428. * @tsl
  17429. * @function
  17430. * @returns {MatcapUVNode}
  17431. */
  17432. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  17433. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  17434. /**
  17435. * Node material version of {@link MeshMatcapMaterial}.
  17436. *
  17437. * @augments NodeMaterial
  17438. */
  17439. class MeshMatcapNodeMaterial extends NodeMaterial {
  17440. static get type() {
  17441. return 'MeshMatcapNodeMaterial';
  17442. }
  17443. /**
  17444. * Constructs a new mesh normal node material.
  17445. *
  17446. * @param {Object} [parameters] - The configuration parameter.
  17447. */
  17448. constructor( parameters ) {
  17449. super();
  17450. /**
  17451. * This flag can be used for type testing.
  17452. *
  17453. * @type {boolean}
  17454. * @readonly
  17455. * @default true
  17456. */
  17457. this.isMeshMatcapNodeMaterial = true;
  17458. this.setDefaultValues( _defaultValues$3 );
  17459. this.setValues( parameters );
  17460. }
  17461. /**
  17462. * Setups the matcap specific node variables.
  17463. *
  17464. * @param {NodeBuilder} builder - The current node builder.
  17465. */
  17466. setupVariants( builder ) {
  17467. const uv = matcapUV;
  17468. let matcapColor;
  17469. if ( builder.material.matcap ) {
  17470. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  17471. } else {
  17472. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  17473. }
  17474. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  17475. }
  17476. }
  17477. /**
  17478. * Applies a rotation to the given position node.
  17479. *
  17480. * @augments TempNode
  17481. */
  17482. class RotateNode extends TempNode {
  17483. static get type() {
  17484. return 'RotateNode';
  17485. }
  17486. /**
  17487. * Constructs a new rotate node.
  17488. *
  17489. * @param {Node} positionNode - The position node.
  17490. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17491. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17492. */
  17493. constructor( positionNode, rotationNode ) {
  17494. super();
  17495. /**
  17496. * The position node.
  17497. *
  17498. * @type {Node}
  17499. */
  17500. this.positionNode = positionNode;
  17501. /**
  17502. * Represents the rotation that is applied to the position node.
  17503. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17504. *
  17505. * @type {Node}
  17506. */
  17507. this.rotationNode = rotationNode;
  17508. }
  17509. /**
  17510. * The type of the {@link RotateNode#positionNode} defines the node's type.
  17511. *
  17512. * @param {NodeBuilder} builder - The current node builder.
  17513. * @return {string} The node's type.
  17514. */
  17515. getNodeType( builder ) {
  17516. return this.positionNode.getNodeType( builder );
  17517. }
  17518. setup( builder ) {
  17519. const { rotationNode, positionNode } = this;
  17520. const nodeType = this.getNodeType( builder );
  17521. if ( nodeType === 'vec2' ) {
  17522. const cosAngle = rotationNode.cos();
  17523. const sinAngle = rotationNode.sin();
  17524. const rotationMatrix = mat2(
  17525. cosAngle, sinAngle,
  17526. sinAngle.negate(), cosAngle
  17527. );
  17528. return rotationMatrix.mul( positionNode );
  17529. } else {
  17530. const rotation = rotationNode;
  17531. 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 ) );
  17532. 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 ) );
  17533. 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 ) );
  17534. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  17535. }
  17536. }
  17537. }
  17538. /**
  17539. * TSL function for creating a rotate node.
  17540. *
  17541. * @tsl
  17542. * @function
  17543. * @param {Node} positionNode - The position node.
  17544. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17545. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17546. * @returns {RotateNode}
  17547. */
  17548. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  17549. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  17550. /**
  17551. * Node material version of {@link SpriteMaterial}.
  17552. *
  17553. * @augments NodeMaterial
  17554. */
  17555. class SpriteNodeMaterial extends NodeMaterial {
  17556. static get type() {
  17557. return 'SpriteNodeMaterial';
  17558. }
  17559. /**
  17560. * Constructs a new sprite node material.
  17561. *
  17562. * @param {Object} [parameters] - The configuration parameter.
  17563. */
  17564. constructor( parameters ) {
  17565. super();
  17566. /**
  17567. * This flag can be used for type testing.
  17568. *
  17569. * @type {boolean}
  17570. * @readonly
  17571. * @default true
  17572. */
  17573. this.isSpriteNodeMaterial = true;
  17574. this._useSizeAttenuation = true;
  17575. /**
  17576. * This property makes it possible to define the position of the sprite with a
  17577. * node. That can be useful when the material is used with instanced rendering
  17578. * and node data are defined with an instanced attribute node:
  17579. * ```js
  17580. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  17581. * material.positionNode = instancedBufferAttribute( positionAttribute );
  17582. * ```
  17583. * Another possibility is to compute the instanced data with a compute shader:
  17584. * ```js
  17585. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  17586. * particleMaterial.positionNode = positionBuffer.toAttribute();
  17587. * ```
  17588. *
  17589. * @type {?Node<vec2>}
  17590. * @default null
  17591. */
  17592. this.positionNode = null;
  17593. /**
  17594. * The rotation of sprite materials is by default inferred from the `rotation`,
  17595. * property. This node property allows to overwrite the default and define
  17596. * the rotation with a node instead.
  17597. *
  17598. * If you don't want to overwrite the rotation but modify the existing
  17599. * value instead, use {@link materialRotation}.
  17600. *
  17601. * @type {?Node<float>}
  17602. * @default null
  17603. */
  17604. this.rotationNode = null;
  17605. /**
  17606. * This node property provides an additional way to scale sprites next to
  17607. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  17608. * is multiplied with the scale value of this node in the vertex shader.
  17609. *
  17610. * @type {?Node<vec2>}
  17611. * @default null
  17612. */
  17613. this.scaleNode = null;
  17614. /**
  17615. * In Sprites, the transparent property is enabled by default.
  17616. *
  17617. * @type {boolean}
  17618. * @default true
  17619. */
  17620. this.transparent = true;
  17621. this.setDefaultValues( _defaultValues$2 );
  17622. this.setValues( parameters );
  17623. }
  17624. /**
  17625. * Setups the position node in view space. This method implements
  17626. * the sprite specific vertex shader.
  17627. *
  17628. * @param {NodeBuilder} builder - The current node builder.
  17629. * @return {Node<vec3>} The position in view space.
  17630. */
  17631. setupPositionView( builder ) {
  17632. const { object, camera } = builder;
  17633. const sizeAttenuation = this.sizeAttenuation;
  17634. const { positionNode, rotationNode, scaleNode } = this;
  17635. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  17636. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  17637. if ( scaleNode !== null ) {
  17638. scale = scale.mul( vec2( scaleNode ) );
  17639. }
  17640. if ( sizeAttenuation === false ) {
  17641. if ( camera.isPerspectiveCamera ) {
  17642. scale = scale.mul( mvPosition.z.negate() );
  17643. } else {
  17644. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  17645. scale = scale.mul( orthoScale.mul( 2 ) );
  17646. }
  17647. }
  17648. let alignedPosition = positionGeometry.xy;
  17649. if ( object.center && object.center.isVector2 === true ) {
  17650. const center = reference$1( 'center', 'vec2', object );
  17651. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  17652. }
  17653. alignedPosition = alignedPosition.mul( scale );
  17654. const rotation = float( rotationNode || materialRotation );
  17655. const rotatedPosition = rotate( alignedPosition, rotation );
  17656. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  17657. }
  17658. copy( source ) {
  17659. this.positionNode = source.positionNode;
  17660. this.rotationNode = source.rotationNode;
  17661. this.scaleNode = source.scaleNode;
  17662. return super.copy( source );
  17663. }
  17664. /**
  17665. * Whether to use size attenuation or not.
  17666. *
  17667. * @type {boolean}
  17668. * @default true
  17669. */
  17670. get sizeAttenuation() {
  17671. return this._useSizeAttenuation;
  17672. }
  17673. set sizeAttenuation( value ) {
  17674. if ( this._useSizeAttenuation !== value ) {
  17675. this._useSizeAttenuation = value;
  17676. this.needsUpdate = true;
  17677. }
  17678. }
  17679. }
  17680. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  17681. /**
  17682. * Node material version of {@link PointsMaterial}.
  17683. *
  17684. * @augments SpriteNodeMaterial
  17685. */
  17686. class PointsNodeMaterial extends SpriteNodeMaterial {
  17687. static get type() {
  17688. return 'PointsNodeMaterial';
  17689. }
  17690. /**
  17691. * Constructs a new points node material.
  17692. *
  17693. * @param {Object} [parameters] - The configuration parameter.
  17694. */
  17695. constructor( parameters ) {
  17696. super();
  17697. /**
  17698. * This node property provides an additional way to set the point size.
  17699. *
  17700. * @type {?Node<vec2>}
  17701. * @default null
  17702. */
  17703. this.sizeNode = null;
  17704. /**
  17705. * This flag can be used for type testing.
  17706. *
  17707. * @type {boolean}
  17708. * @readonly
  17709. * @default true
  17710. */
  17711. this.isPointsNodeMaterial = true;
  17712. this.setDefaultValues( _defaultValues$1 );
  17713. this.setValues( parameters );
  17714. }
  17715. setupPositionView() {
  17716. const { positionNode } = this;
  17717. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  17718. }
  17719. setupVertex( builder ) {
  17720. const mvp = super.setupVertex( builder );
  17721. // skip further processing if the material is not a node material
  17722. if ( builder.material.isNodeMaterial !== true ) {
  17723. return mvp;
  17724. }
  17725. // ndc space
  17726. const { rotationNode, scaleNode, sizeNode } = this;
  17727. const alignedPosition = positionGeometry.xy.toVar();
  17728. const aspect = viewport.z.div( viewport.w );
  17729. // rotation
  17730. if ( rotationNode && rotationNode.isNode ) {
  17731. const rotation = float( rotationNode );
  17732. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  17733. }
  17734. // point size
  17735. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  17736. if ( this.sizeAttenuation === true ) {
  17737. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  17738. }
  17739. // scale
  17740. if ( scaleNode && scaleNode.isNode ) {
  17741. pointSize = pointSize.mul( vec2( scaleNode ) );
  17742. }
  17743. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  17744. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  17745. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  17746. // back to clip space
  17747. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  17748. //clipPos.xy += offset;
  17749. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  17750. return mvp;
  17751. }
  17752. /**
  17753. * Whether alpha to coverage should be used or not.
  17754. *
  17755. * @type {boolean}
  17756. * @default true
  17757. */
  17758. get alphaToCoverage() {
  17759. return this._useAlphaToCoverage;
  17760. }
  17761. set alphaToCoverage( value ) {
  17762. if ( this._useAlphaToCoverage !== value ) {
  17763. this._useAlphaToCoverage = value;
  17764. this.needsUpdate = true;
  17765. }
  17766. }
  17767. }
  17768. /**
  17769. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  17770. *
  17771. * @augments LightingModel
  17772. */
  17773. class ShadowMaskModel extends LightingModel {
  17774. /**
  17775. * Constructs a new shadow mask model.
  17776. */
  17777. constructor() {
  17778. super();
  17779. /**
  17780. * The shadow mask node.
  17781. *
  17782. * @type {Node}
  17783. */
  17784. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  17785. }
  17786. /**
  17787. * Only used to save the shadow mask.
  17788. *
  17789. * @param {Object} input - The input data.
  17790. */
  17791. direct( { lightNode } ) {
  17792. this.shadowNode.mulAssign( lightNode.shadowNode );
  17793. }
  17794. /**
  17795. * Uses the shadow mask to produce the final color.
  17796. *
  17797. * @param {NodeBuilder} builder - The current node builder.
  17798. */
  17799. finish( { context } ) {
  17800. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  17801. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  17802. }
  17803. }
  17804. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  17805. /**
  17806. * Node material version of {@link ShadowMaterial}.
  17807. *
  17808. * @augments NodeMaterial
  17809. */
  17810. class ShadowNodeMaterial extends NodeMaterial {
  17811. static get type() {
  17812. return 'ShadowNodeMaterial';
  17813. }
  17814. /**
  17815. * Constructs a new shadow node material.
  17816. *
  17817. * @param {Object} [parameters] - The configuration parameter.
  17818. */
  17819. constructor( parameters ) {
  17820. super();
  17821. /**
  17822. * This flag can be used for type testing.
  17823. *
  17824. * @type {boolean}
  17825. * @readonly
  17826. * @default true
  17827. */
  17828. this.isShadowNodeMaterial = true;
  17829. /**
  17830. * Set to `true` because so it's possible to implement
  17831. * the shadow mask effect.
  17832. *
  17833. * @type {boolean}
  17834. * @default true
  17835. */
  17836. this.lights = true;
  17837. /**
  17838. * Overwritten since shadow materials are transparent
  17839. * by default.
  17840. *
  17841. * @type {boolean}
  17842. * @default true
  17843. */
  17844. this.transparent = true;
  17845. this.setDefaultValues( _defaultValues );
  17846. this.setValues( parameters );
  17847. }
  17848. /**
  17849. * Setups the lighting model.
  17850. *
  17851. * @return {ShadowMaskModel} The lighting model.
  17852. */
  17853. setupLightingModel( /*builder*/ ) {
  17854. return new ShadowMaskModel();
  17855. }
  17856. }
  17857. const scatteringDensity = property( 'vec3' );
  17858. const linearDepthRay = property( 'vec3' );
  17859. const outgoingRayLight = property( 'vec3' );
  17860. /**
  17861. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  17862. * This model calculates the scattering and transmittance of light through a volumetric medium.
  17863. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  17864. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  17865. *
  17866. * @augments LightingModel
  17867. */
  17868. class VolumetricLightingModel extends LightingModel {
  17869. constructor() {
  17870. super();
  17871. }
  17872. start( builder ) {
  17873. const { material, context } = builder;
  17874. const startPos = property( 'vec3' );
  17875. const endPos = property( 'vec3' );
  17876. // This approach dynamically changes the direction of the ray,
  17877. // prioritizing the ray from the camera to the object if it is inside the mesh, and from the object to the camera if it is far away.
  17878. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  17879. startPos.assign( cameraPosition );
  17880. endPos.assign( positionWorld );
  17881. } ).Else( () => {
  17882. startPos.assign( positionWorld );
  17883. endPos.assign( cameraPosition );
  17884. } );
  17885. //
  17886. const viewVector = endPos.sub( startPos );
  17887. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  17888. const stepSize = viewVector.length().div( steps ).toVar();
  17889. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  17890. const distTravelled = float( 0.0 ).toVar();
  17891. const transmittance = vec3( 1 ).toVar();
  17892. if ( material.offsetNode ) {
  17893. // reduce banding
  17894. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  17895. }
  17896. Loop( steps, () => {
  17897. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  17898. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  17899. if ( material.depthNode !== null ) {
  17900. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  17901. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  17902. }
  17903. context.positionWorld = positionRay;
  17904. context.shadowPositionWorld = positionRay;
  17905. context.positionView = positionViewRay;
  17906. scatteringDensity.assign( 0 );
  17907. let scatteringNode;
  17908. if ( material.scatteringNode ) {
  17909. scatteringNode = material.scatteringNode( {
  17910. positionRay
  17911. } );
  17912. }
  17913. super.start( builder );
  17914. if ( scatteringNode ) {
  17915. scatteringDensity.mulAssign( scatteringNode );
  17916. }
  17917. // beer's law
  17918. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  17919. transmittance.mulAssign( falloff );
  17920. // move along the ray
  17921. distTravelled.addAssign( stepSize );
  17922. } );
  17923. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  17924. }
  17925. scatteringLight( lightColor, builder ) {
  17926. const sceneDepthNode = builder.context.sceneDepthNode;
  17927. if ( sceneDepthNode ) {
  17928. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  17929. scatteringDensity.addAssign( lightColor );
  17930. } );
  17931. } else {
  17932. scatteringDensity.addAssign( lightColor );
  17933. }
  17934. }
  17935. direct( { lightNode, lightColor }, builder ) {
  17936. // Ignore lights with infinite distance
  17937. if ( lightNode.light.distance === undefined ) return;
  17938. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  17939. const directLight = lightColor.xyz.toVar();
  17940. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  17941. this.scatteringLight( directLight, builder );
  17942. }
  17943. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  17944. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  17945. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  17946. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  17947. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  17948. const P = builder.context.positionView;
  17949. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  17950. this.scatteringLight( directLight, builder );
  17951. }
  17952. finish( builder ) {
  17953. builder.context.outgoingLight.assign( outgoingRayLight );
  17954. }
  17955. }
  17956. /**
  17957. * Volume node material.
  17958. *
  17959. * @augments NodeMaterial
  17960. */
  17961. class VolumeNodeMaterial extends NodeMaterial {
  17962. static get type() {
  17963. return 'VolumeNodeMaterial';
  17964. }
  17965. /**
  17966. * Constructs a new volume node material.
  17967. *
  17968. * @param {Object} [parameters] - The configuration parameter.
  17969. */
  17970. constructor( parameters ) {
  17971. super();
  17972. /**
  17973. * This flag can be used for type testing.
  17974. *
  17975. * @type {boolean}
  17976. * @readonly
  17977. * @default true
  17978. */
  17979. this.isVolumeNodeMaterial = true;
  17980. /**
  17981. * Number of steps used for raymarching.
  17982. *
  17983. * @type {number}
  17984. * @default 25
  17985. */
  17986. this.steps = 25;
  17987. /**
  17988. * Offsets the distance a ray has been traveled through a volume.
  17989. * Can be used to implement dithering to reduce banding.
  17990. *
  17991. * @type {Node<float>}
  17992. * @default null
  17993. */
  17994. this.offsetNode = null;
  17995. /**
  17996. * Node used for scattering calculations.
  17997. *
  17998. * @type {Function|FunctionNode<vec4>}
  17999. * @default null
  18000. */
  18001. this.scatteringNode = null;
  18002. this.lights = true;
  18003. this.transparent = true;
  18004. this.side = BackSide;
  18005. this.depthTest = false;
  18006. this.depthWrite = false;
  18007. this.setValues( parameters );
  18008. }
  18009. setupLightingModel() {
  18010. return new VolumetricLightingModel();
  18011. }
  18012. }
  18013. /**
  18014. * This module manages the internal animation loop of the renderer.
  18015. *
  18016. * @private
  18017. */
  18018. class Animation {
  18019. /**
  18020. * Constructs a new animation loop management component.
  18021. *
  18022. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18023. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18024. */
  18025. constructor( nodes, info ) {
  18026. /**
  18027. * Renderer component for managing nodes related logic.
  18028. *
  18029. * @type {Nodes}
  18030. */
  18031. this.nodes = nodes;
  18032. /**
  18033. * Renderer component for managing metrics and monitoring data.
  18034. *
  18035. * @type {Info}
  18036. */
  18037. this.info = info;
  18038. /**
  18039. * A reference to the context from `requestAnimationFrame()` can
  18040. * be called (usually `window`).
  18041. *
  18042. * @type {?(Window|XRSession)}
  18043. */
  18044. this._context = typeof self !== 'undefined' ? self : null;
  18045. /**
  18046. * The user-defined animation loop.
  18047. *
  18048. * @type {?Function}
  18049. * @default null
  18050. */
  18051. this._animationLoop = null;
  18052. /**
  18053. * The requestId which is returned from the `requestAnimationFrame()` call.
  18054. * Can be used to cancel the stop the animation loop.
  18055. *
  18056. * @type {?number}
  18057. * @default null
  18058. */
  18059. this._requestId = null;
  18060. }
  18061. /**
  18062. * Starts the internal animation loop.
  18063. */
  18064. start() {
  18065. const update = ( time, xrFrame ) => {
  18066. this._requestId = this._context.requestAnimationFrame( update );
  18067. if ( this.info.autoReset === true ) this.info.reset();
  18068. this.nodes.nodeFrame.update();
  18069. this.info.frame = this.nodes.nodeFrame.frameId;
  18070. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  18071. };
  18072. update();
  18073. }
  18074. /**
  18075. * Stops the internal animation loop.
  18076. */
  18077. stop() {
  18078. this._context.cancelAnimationFrame( this._requestId );
  18079. this._requestId = null;
  18080. }
  18081. /**
  18082. * Returns the user-level animation loop.
  18083. *
  18084. * @return {?Function} The animation loop.
  18085. */
  18086. getAnimationLoop() {
  18087. return this._animationLoop;
  18088. }
  18089. /**
  18090. * Defines the user-level animation loop.
  18091. *
  18092. * @param {?Function} callback - The animation loop.
  18093. */
  18094. setAnimationLoop( callback ) {
  18095. this._animationLoop = callback;
  18096. }
  18097. /**
  18098. * Returns the animation context.
  18099. *
  18100. * @return {Window|XRSession} The animation context.
  18101. */
  18102. getContext() {
  18103. return this._context;
  18104. }
  18105. /**
  18106. * Defines the context in which `requestAnimationFrame()` is executed.
  18107. *
  18108. * @param {Window|XRSession} context - The context to set.
  18109. */
  18110. setContext( context ) {
  18111. this._context = context;
  18112. }
  18113. /**
  18114. * Frees all internal resources and stops the animation loop.
  18115. */
  18116. dispose() {
  18117. this.stop();
  18118. }
  18119. }
  18120. /**
  18121. * Data structure for the renderer. It allows defining values
  18122. * with chained, hierarchical keys. Keys are meant to be
  18123. * objects since the module internally works with Weak Maps
  18124. * for performance reasons.
  18125. *
  18126. * @private
  18127. */
  18128. class ChainMap {
  18129. /**
  18130. * Constructs a new Chain Map.
  18131. */
  18132. constructor() {
  18133. /**
  18134. * The root Weak Map.
  18135. *
  18136. * @type {WeakMap}
  18137. */
  18138. this.weakMap = new WeakMap();
  18139. }
  18140. /**
  18141. * Returns the value for the given array of keys.
  18142. *
  18143. * @param {Array<Object>} keys - List of keys.
  18144. * @return {any} The value. Returns `undefined` if no value was found.
  18145. */
  18146. get( keys ) {
  18147. let map = this.weakMap;
  18148. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18149. map = map.get( keys[ i ] );
  18150. if ( map === undefined ) return undefined;
  18151. }
  18152. return map.get( keys[ keys.length - 1 ] );
  18153. }
  18154. /**
  18155. * Sets the value for the given keys.
  18156. *
  18157. * @param {Array<Object>} keys - List of keys.
  18158. * @param {any} value - The value to set.
  18159. * @return {ChainMap} A reference to this Chain Map.
  18160. */
  18161. set( keys, value ) {
  18162. let map = this.weakMap;
  18163. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18164. const key = keys[ i ];
  18165. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  18166. map = map.get( key );
  18167. }
  18168. map.set( keys[ keys.length - 1 ], value );
  18169. return this;
  18170. }
  18171. /**
  18172. * Deletes a value for the given keys.
  18173. *
  18174. * @param {Array<Object>} keys - The keys.
  18175. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  18176. */
  18177. delete( keys ) {
  18178. let map = this.weakMap;
  18179. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18180. map = map.get( keys[ i ] );
  18181. if ( map === undefined ) return false;
  18182. }
  18183. return map.delete( keys[ keys.length - 1 ] );
  18184. }
  18185. }
  18186. let _id$9 = 0;
  18187. function getKeys( obj ) {
  18188. const keys = Object.keys( obj );
  18189. let proto = Object.getPrototypeOf( obj );
  18190. while ( proto ) {
  18191. const descriptors = Object.getOwnPropertyDescriptors( proto );
  18192. for ( const key in descriptors ) {
  18193. if ( descriptors[ key ] !== undefined ) {
  18194. const descriptor = descriptors[ key ];
  18195. if ( descriptor && typeof descriptor.get === 'function' ) {
  18196. keys.push( key );
  18197. }
  18198. }
  18199. }
  18200. proto = Object.getPrototypeOf( proto );
  18201. }
  18202. return keys;
  18203. }
  18204. /**
  18205. * A render object is the renderer's representation of single entity that gets drawn
  18206. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  18207. * scene since render objects also depend from the used material, the current render context
  18208. * and the current scene's lighting.
  18209. *
  18210. * In general, the basic process of the renderer is:
  18211. *
  18212. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  18213. * - Process the render lists by calling one or more render commands for each render item.
  18214. * - For each render command, request a render object and perform the draw.
  18215. *
  18216. * The module provides an interface to get data required for the draw command like the actual
  18217. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  18218. * creating render objects should only be done when necessary.
  18219. *
  18220. * @private
  18221. */
  18222. class RenderObject {
  18223. /**
  18224. * Constructs a new render object.
  18225. *
  18226. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18227. * @param {Geometries} geometries - Renderer component for managing geometries.
  18228. * @param {Renderer} renderer - The renderer.
  18229. * @param {Object3D} object - The 3D object.
  18230. * @param {Material} material - The 3D object's material.
  18231. * @param {Scene} scene - The scene the 3D object belongs to.
  18232. * @param {Camera} camera - The camera the object should be rendered with.
  18233. * @param {LightsNode} lightsNode - The lights node.
  18234. * @param {RenderContext} renderContext - The render context.
  18235. * @param {ClippingContext} clippingContext - The clipping context.
  18236. */
  18237. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  18238. this.id = _id$9 ++;
  18239. /**
  18240. * Renderer component for managing nodes related logic.
  18241. *
  18242. * @type {Nodes}
  18243. * @private
  18244. */
  18245. this._nodes = nodes;
  18246. /**
  18247. * Renderer component for managing geometries.
  18248. *
  18249. * @type {Geometries}
  18250. * @private
  18251. */
  18252. this._geometries = geometries;
  18253. /**
  18254. * The renderer.
  18255. *
  18256. * @type {Renderer}
  18257. */
  18258. this.renderer = renderer;
  18259. /**
  18260. * The 3D object.
  18261. *
  18262. * @type {Object3D}
  18263. */
  18264. this.object = object;
  18265. /**
  18266. * The 3D object's material.
  18267. *
  18268. * @type {Material}
  18269. */
  18270. this.material = material;
  18271. /**
  18272. * The scene the 3D object belongs to.
  18273. *
  18274. * @type {Scene}
  18275. */
  18276. this.scene = scene;
  18277. /**
  18278. * The camera the 3D object should be rendered with.
  18279. *
  18280. * @type {Camera}
  18281. */
  18282. this.camera = camera;
  18283. /**
  18284. * The lights node.
  18285. *
  18286. * @type {LightsNode}
  18287. */
  18288. this.lightsNode = lightsNode;
  18289. /**
  18290. * The render context.
  18291. *
  18292. * @type {RenderContext}
  18293. */
  18294. this.context = renderContext;
  18295. /**
  18296. * The 3D object's geometry.
  18297. *
  18298. * @type {BufferGeometry}
  18299. */
  18300. this.geometry = object.geometry;
  18301. /**
  18302. * The render object's version.
  18303. *
  18304. * @type {number}
  18305. */
  18306. this.version = material.version;
  18307. /**
  18308. * The draw range of the geometry.
  18309. *
  18310. * @type {?Object}
  18311. * @default null
  18312. */
  18313. this.drawRange = null;
  18314. /**
  18315. * An array holding the buffer attributes
  18316. * of the render object. This entails attribute
  18317. * definitions on geometry and node level.
  18318. *
  18319. * @type {?Array<BufferAttribute>}
  18320. * @default null
  18321. */
  18322. this.attributes = null;
  18323. /**
  18324. * A reference to a render pipeline the render
  18325. * object is processed with.
  18326. *
  18327. * @type {RenderPipeline}
  18328. * @default null
  18329. */
  18330. this.pipeline = null;
  18331. /**
  18332. * Only relevant for objects using
  18333. * multiple materials. This represents a group entry
  18334. * from the respective `BufferGeometry`.
  18335. *
  18336. * @type {?{start: number, count: number}}
  18337. * @default null
  18338. */
  18339. this.group = null;
  18340. /**
  18341. * An array holding the vertex buffers which can
  18342. * be buffer attributes but also interleaved buffers.
  18343. *
  18344. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  18345. * @default null
  18346. */
  18347. this.vertexBuffers = null;
  18348. /**
  18349. * The parameters for the draw command.
  18350. *
  18351. * @type {?Object}
  18352. * @default null
  18353. */
  18354. this.drawParams = null;
  18355. /**
  18356. * If this render object is used inside a render bundle,
  18357. * this property points to the respective bundle group.
  18358. *
  18359. * @type {?BundleGroup}
  18360. * @default null
  18361. */
  18362. this.bundle = null;
  18363. /**
  18364. * The clipping context.
  18365. *
  18366. * @type {ClippingContext}
  18367. */
  18368. this.clippingContext = clippingContext;
  18369. /**
  18370. * The clipping context's cache key.
  18371. *
  18372. * @type {string}
  18373. */
  18374. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  18375. /**
  18376. * The initial node cache key.
  18377. *
  18378. * @type {number}
  18379. */
  18380. this.initialNodesCacheKey = this.getDynamicCacheKey();
  18381. /**
  18382. * The initial cache key.
  18383. *
  18384. * @type {number}
  18385. */
  18386. this.initialCacheKey = this.getCacheKey();
  18387. /**
  18388. * The node builder state.
  18389. *
  18390. * @type {?NodeBuilderState}
  18391. * @private
  18392. * @default null
  18393. */
  18394. this._nodeBuilderState = null;
  18395. /**
  18396. * An array of bindings.
  18397. *
  18398. * @type {?Array<BindGroup>}
  18399. * @private
  18400. * @default null
  18401. */
  18402. this._bindings = null;
  18403. /**
  18404. * Reference to the node material observer.
  18405. *
  18406. * @type {?NodeMaterialObserver}
  18407. * @private
  18408. * @default null
  18409. */
  18410. this._monitor = null;
  18411. /**
  18412. * An event listener which is defined by `RenderObjects`. It performs
  18413. * clean up tasks when `dispose()` on this render object.
  18414. *
  18415. * @method
  18416. */
  18417. this.onDispose = null;
  18418. /**
  18419. * This flag can be used for type testing.
  18420. *
  18421. * @type {boolean}
  18422. * @readonly
  18423. * @default true
  18424. */
  18425. this.isRenderObject = true;
  18426. /**
  18427. * An event listener which is executed when `dispose()` is called on
  18428. * the render object's material.
  18429. *
  18430. * @method
  18431. */
  18432. this.onMaterialDispose = () => {
  18433. this.dispose();
  18434. };
  18435. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  18436. }
  18437. /**
  18438. * Updates the clipping context.
  18439. *
  18440. * @param {ClippingContext} context - The clipping context to set.
  18441. */
  18442. updateClipping( context ) {
  18443. this.clippingContext = context;
  18444. }
  18445. /**
  18446. * Whether the clipping requires an update or not.
  18447. *
  18448. * @type {boolean}
  18449. * @readonly
  18450. */
  18451. get clippingNeedsUpdate() {
  18452. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  18453. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  18454. return true;
  18455. }
  18456. /**
  18457. * The number of clipping planes defined in context of hardware clipping.
  18458. *
  18459. * @type {number}
  18460. * @readonly
  18461. */
  18462. get hardwareClippingPlanes() {
  18463. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  18464. }
  18465. /**
  18466. * Returns the node builder state of this render object.
  18467. *
  18468. * @return {NodeBuilderState} The node builder state.
  18469. */
  18470. getNodeBuilderState() {
  18471. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  18472. }
  18473. /**
  18474. * Returns the node material observer of this render object.
  18475. *
  18476. * @return {NodeMaterialObserver} The node material observer.
  18477. */
  18478. getMonitor() {
  18479. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  18480. }
  18481. /**
  18482. * Returns an array of bind groups of this render object.
  18483. *
  18484. * @return {Array<BindGroup>} The bindings.
  18485. */
  18486. getBindings() {
  18487. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  18488. }
  18489. /**
  18490. * Returns a binding group by group name of this render object.
  18491. *
  18492. * @param {string} name - The name of the binding group.
  18493. * @return {?BindGroup} The bindings.
  18494. */
  18495. getBindingGroup( name ) {
  18496. for ( const bindingGroup of this.getBindings() ) {
  18497. if ( bindingGroup.name === name ) {
  18498. return bindingGroup;
  18499. }
  18500. }
  18501. }
  18502. /**
  18503. * Returns the index of the render object's geometry.
  18504. *
  18505. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  18506. */
  18507. getIndex() {
  18508. return this._geometries.getIndex( this );
  18509. }
  18510. /**
  18511. * Returns the indirect buffer attribute.
  18512. *
  18513. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  18514. */
  18515. getIndirect() {
  18516. return this._geometries.getIndirect( this );
  18517. }
  18518. /**
  18519. * Returns an array that acts as a key for identifying the render object in a chain map.
  18520. *
  18521. * @return {Array<Object>} An array with object references.
  18522. */
  18523. getChainArray() {
  18524. return [ this.object, this.material, this.context, this.lightsNode ];
  18525. }
  18526. /**
  18527. * This method is used when the geometry of a 3D object has been exchanged and the
  18528. * respective render object now requires an update.
  18529. *
  18530. * @param {BufferGeometry} geometry - The geometry to set.
  18531. */
  18532. setGeometry( geometry ) {
  18533. this.geometry = geometry;
  18534. this.attributes = null;
  18535. }
  18536. /**
  18537. * Returns the buffer attributes of the render object. The returned array holds
  18538. * attribute definitions on geometry and node level.
  18539. *
  18540. * @return {Array<BufferAttribute>} An array with buffer attributes.
  18541. */
  18542. getAttributes() {
  18543. if ( this.attributes !== null ) return this.attributes;
  18544. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  18545. const geometry = this.geometry;
  18546. const attributes = [];
  18547. const vertexBuffers = new Set();
  18548. for ( const nodeAttribute of nodeAttributes ) {
  18549. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  18550. if ( attribute === undefined ) continue;
  18551. attributes.push( attribute );
  18552. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  18553. vertexBuffers.add( bufferAttribute );
  18554. }
  18555. this.attributes = attributes;
  18556. this.vertexBuffers = Array.from( vertexBuffers.values() );
  18557. return attributes;
  18558. }
  18559. /**
  18560. * Returns the vertex buffers of the render object.
  18561. *
  18562. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  18563. */
  18564. getVertexBuffers() {
  18565. if ( this.vertexBuffers === null ) this.getAttributes();
  18566. return this.vertexBuffers;
  18567. }
  18568. /**
  18569. * Returns the draw parameters for the render object.
  18570. *
  18571. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  18572. */
  18573. getDrawParameters() {
  18574. const { object, material, geometry, group, drawRange } = this;
  18575. const drawParams = this.drawParams || ( this.drawParams = {
  18576. vertexCount: 0,
  18577. firstVertex: 0,
  18578. instanceCount: 0,
  18579. firstInstance: 0
  18580. } );
  18581. const index = this.getIndex();
  18582. const hasIndex = ( index !== null );
  18583. let instanceCount = 1;
  18584. if ( geometry.isInstancedBufferGeometry === true ) {
  18585. instanceCount = geometry.instanceCount;
  18586. } else if ( object.count !== undefined ) {
  18587. instanceCount = Math.max( 0, object.count );
  18588. }
  18589. if ( instanceCount === 0 ) return null;
  18590. drawParams.instanceCount = instanceCount;
  18591. if ( object.isBatchedMesh === true ) return drawParams;
  18592. let rangeFactor = 1;
  18593. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  18594. rangeFactor = 2;
  18595. }
  18596. let firstVertex = drawRange.start * rangeFactor;
  18597. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  18598. if ( group !== null ) {
  18599. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  18600. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  18601. }
  18602. const position = geometry.attributes.position;
  18603. let itemCount = Infinity;
  18604. if ( hasIndex ) {
  18605. itemCount = index.count;
  18606. } else if ( position !== undefined && position !== null ) {
  18607. itemCount = position.count;
  18608. }
  18609. firstVertex = Math.max( firstVertex, 0 );
  18610. lastVertex = Math.min( lastVertex, itemCount );
  18611. const count = lastVertex - firstVertex;
  18612. if ( count < 0 || count === Infinity ) return null;
  18613. drawParams.vertexCount = count;
  18614. drawParams.firstVertex = firstVertex;
  18615. return drawParams;
  18616. }
  18617. /**
  18618. * Returns the render object's geometry cache key.
  18619. *
  18620. * The geometry cache key is part of the material cache key.
  18621. *
  18622. * @return {string} The geometry cache key.
  18623. */
  18624. getGeometryCacheKey() {
  18625. const { geometry } = this;
  18626. let cacheKey = '';
  18627. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  18628. const attribute = geometry.attributes[ name ];
  18629. cacheKey += name + ',';
  18630. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  18631. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  18632. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  18633. if ( attribute.normalized ) cacheKey += 'n,';
  18634. }
  18635. // structural equality isn't sufficient for morph targets since the
  18636. // data are maintained in textures. only if the targets are all equal
  18637. // the texture and thus the instance of `MorphNode` can be shared.
  18638. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  18639. const targets = geometry.morphAttributes[ name ];
  18640. cacheKey += 'morph-' + name + ',';
  18641. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  18642. const attribute = targets[ i ];
  18643. cacheKey += attribute.id + ',';
  18644. }
  18645. }
  18646. if ( geometry.index ) {
  18647. cacheKey += 'index,';
  18648. }
  18649. return cacheKey;
  18650. }
  18651. /**
  18652. * Returns the render object's material cache key.
  18653. *
  18654. * The material cache key is part of the render object cache key.
  18655. *
  18656. * @return {number} The material cache key.
  18657. */
  18658. getMaterialCacheKey() {
  18659. const { object, material } = this;
  18660. let cacheKey = material.customProgramCacheKey();
  18661. for ( const property of getKeys( material ) ) {
  18662. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  18663. const value = material[ property ];
  18664. let valueKey;
  18665. if ( value !== null ) {
  18666. // some material values require a formatting
  18667. const type = typeof value;
  18668. if ( type === 'number' ) {
  18669. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  18670. } else if ( type === 'object' ) {
  18671. valueKey = '{';
  18672. if ( value.isTexture ) {
  18673. valueKey += value.mapping;
  18674. }
  18675. valueKey += '}';
  18676. } else {
  18677. valueKey = String( value );
  18678. }
  18679. } else {
  18680. valueKey = String( value );
  18681. }
  18682. cacheKey += /*property + ':' +*/ valueKey + ',';
  18683. }
  18684. cacheKey += this.clippingContextCacheKey + ',';
  18685. if ( object.geometry ) {
  18686. cacheKey += this.getGeometryCacheKey();
  18687. }
  18688. if ( object.skeleton ) {
  18689. cacheKey += object.skeleton.bones.length + ',';
  18690. }
  18691. if ( object.isBatchedMesh ) {
  18692. cacheKey += object._matricesTexture.uuid + ',';
  18693. if ( object._colorsTexture !== null ) {
  18694. cacheKey += object._colorsTexture.uuid + ',';
  18695. }
  18696. }
  18697. if ( object.count > 1 ) {
  18698. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  18699. cacheKey += object.uuid + ',';
  18700. }
  18701. cacheKey += object.receiveShadow + ',';
  18702. return hashString( cacheKey );
  18703. }
  18704. /**
  18705. * Whether the geometry requires an update or not.
  18706. *
  18707. * @type {boolean}
  18708. * @readonly
  18709. */
  18710. get needsGeometryUpdate() {
  18711. return this.geometry.id !== this.object.geometry.id;
  18712. }
  18713. /**
  18714. * Whether the render object requires an update or not.
  18715. *
  18716. * Note: There are two distinct places where render objects are checked for an update.
  18717. *
  18718. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  18719. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  18720. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  18721. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  18722. * a need for a refresh due to material, geometry or object related value changes.
  18723. *
  18724. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  18725. * that performs the 'needsUpdate' check.
  18726. *
  18727. * @type {boolean}
  18728. * @readonly
  18729. */
  18730. get needsUpdate() {
  18731. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  18732. }
  18733. /**
  18734. * Returns the dynamic cache key which represents a key that is computed per draw command.
  18735. *
  18736. * @return {number} The cache key.
  18737. */
  18738. getDynamicCacheKey() {
  18739. let cacheKey = 0;
  18740. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  18741. // the renderer is inside a shadow pass.
  18742. if ( this.material.isShadowPassMaterial !== true ) {
  18743. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  18744. }
  18745. if ( this.camera.isArrayCamera ) {
  18746. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  18747. }
  18748. if ( this.object.receiveShadow ) {
  18749. cacheKey = hash$1( cacheKey, 1 );
  18750. }
  18751. return cacheKey;
  18752. }
  18753. /**
  18754. * Returns the render object's cache key.
  18755. *
  18756. * @return {number} The cache key.
  18757. */
  18758. getCacheKey() {
  18759. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  18760. }
  18761. /**
  18762. * Frees internal resources.
  18763. */
  18764. dispose() {
  18765. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  18766. this.onDispose();
  18767. }
  18768. }
  18769. const _chainKeys$5 = [];
  18770. /**
  18771. * This module manages the render objects of the renderer.
  18772. *
  18773. * @private
  18774. */
  18775. class RenderObjects {
  18776. /**
  18777. * Constructs a new render object management component.
  18778. *
  18779. * @param {Renderer} renderer - The renderer.
  18780. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18781. * @param {Geometries} geometries - Renderer component for managing geometries.
  18782. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  18783. * @param {Bindings} bindings - Renderer component for managing bindings.
  18784. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18785. */
  18786. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  18787. /**
  18788. * The renderer.
  18789. *
  18790. * @type {Renderer}
  18791. */
  18792. this.renderer = renderer;
  18793. /**
  18794. * Renderer component for managing nodes related logic.
  18795. *
  18796. * @type {Nodes}
  18797. */
  18798. this.nodes = nodes;
  18799. /**
  18800. * Renderer component for managing geometries.
  18801. *
  18802. * @type {Geometries}
  18803. */
  18804. this.geometries = geometries;
  18805. /**
  18806. * Renderer component for managing pipelines.
  18807. *
  18808. * @type {Pipelines}
  18809. */
  18810. this.pipelines = pipelines;
  18811. /**
  18812. * Renderer component for managing bindings.
  18813. *
  18814. * @type {Bindings}
  18815. */
  18816. this.bindings = bindings;
  18817. /**
  18818. * Renderer component for managing metrics and monitoring data.
  18819. *
  18820. * @type {Info}
  18821. */
  18822. this.info = info;
  18823. /**
  18824. * A dictionary that manages render contexts in chain maps
  18825. * for each pass ID.
  18826. *
  18827. * @type {Object<string,ChainMap>}
  18828. */
  18829. this.chainMaps = {};
  18830. }
  18831. /**
  18832. * Returns a render object for the given object and state data.
  18833. *
  18834. * @param {Object3D} object - The 3D object.
  18835. * @param {Material} material - The 3D object's material.
  18836. * @param {Scene} scene - The scene the 3D object belongs to.
  18837. * @param {Camera} camera - The camera the 3D object should be rendered with.
  18838. * @param {LightsNode} lightsNode - The lights node.
  18839. * @param {RenderContext} renderContext - The render context.
  18840. * @param {ClippingContext} clippingContext - The clipping context.
  18841. * @param {string} [passId] - An optional ID for identifying the pass.
  18842. * @return {RenderObject} The render object.
  18843. */
  18844. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  18845. const chainMap = this.getChainMap( passId );
  18846. // reuse chainArray
  18847. _chainKeys$5[ 0 ] = object;
  18848. _chainKeys$5[ 1 ] = material;
  18849. _chainKeys$5[ 2 ] = renderContext;
  18850. _chainKeys$5[ 3 ] = lightsNode;
  18851. let renderObject = chainMap.get( _chainKeys$5 );
  18852. if ( renderObject === undefined ) {
  18853. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  18854. chainMap.set( _chainKeys$5, renderObject );
  18855. } else {
  18856. renderObject.updateClipping( clippingContext );
  18857. if ( renderObject.needsGeometryUpdate ) {
  18858. renderObject.setGeometry( object.geometry );
  18859. }
  18860. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  18861. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  18862. renderObject.dispose();
  18863. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  18864. } else {
  18865. renderObject.version = material.version;
  18866. }
  18867. }
  18868. }
  18869. _chainKeys$5.length = 0;
  18870. return renderObject;
  18871. }
  18872. /**
  18873. * Returns a chain map for the given pass ID.
  18874. *
  18875. * @param {string} [passId='default'] - The pass ID.
  18876. * @return {ChainMap} The chain map.
  18877. */
  18878. getChainMap( passId = 'default' ) {
  18879. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  18880. }
  18881. /**
  18882. * Frees internal resources.
  18883. */
  18884. dispose() {
  18885. this.chainMaps = {};
  18886. }
  18887. /**
  18888. * Factory method for creating render objects with the given list of parameters.
  18889. *
  18890. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18891. * @param {Geometries} geometries - Renderer component for managing geometries.
  18892. * @param {Renderer} renderer - The renderer.
  18893. * @param {Object3D} object - The 3D object.
  18894. * @param {Material} material - The object's material.
  18895. * @param {Scene} scene - The scene the 3D object belongs to.
  18896. * @param {Camera} camera - The camera the object should be rendered with.
  18897. * @param {LightsNode} lightsNode - The lights node.
  18898. * @param {RenderContext} renderContext - The render context.
  18899. * @param {ClippingContext} clippingContext - The clipping context.
  18900. * @param {string} [passId] - An optional ID for identifying the pass.
  18901. * @return {RenderObject} The render object.
  18902. */
  18903. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  18904. const chainMap = this.getChainMap( passId );
  18905. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  18906. renderObject.onDispose = () => {
  18907. this.pipelines.delete( renderObject );
  18908. this.bindings.delete( renderObject );
  18909. this.nodes.delete( renderObject );
  18910. chainMap.delete( renderObject.getChainArray() );
  18911. };
  18912. return renderObject;
  18913. }
  18914. }
  18915. /**
  18916. * Data structure for the renderer. It is intended to manage
  18917. * data of objects in dictionaries.
  18918. *
  18919. * @private
  18920. */
  18921. class DataMap {
  18922. /**
  18923. * Constructs a new data map.
  18924. */
  18925. constructor() {
  18926. /**
  18927. * `DataMap` internally uses a weak map
  18928. * to manage its data.
  18929. *
  18930. * @type {WeakMap}
  18931. */
  18932. this.data = new WeakMap();
  18933. }
  18934. /**
  18935. * Returns the dictionary for the given object.
  18936. *
  18937. * @param {Object} object - The object.
  18938. * @return {Object} The dictionary.
  18939. */
  18940. get( object ) {
  18941. let map = this.data.get( object );
  18942. if ( map === undefined ) {
  18943. map = {};
  18944. this.data.set( object, map );
  18945. }
  18946. return map;
  18947. }
  18948. /**
  18949. * Deletes the dictionary for the given object.
  18950. *
  18951. * @param {Object} object - The object.
  18952. * @return {?Object} The deleted dictionary.
  18953. */
  18954. delete( object ) {
  18955. let map = null;
  18956. if ( this.data.has( object ) ) {
  18957. map = this.data.get( object );
  18958. this.data.delete( object );
  18959. }
  18960. return map;
  18961. }
  18962. /**
  18963. * Returns `true` if the given object has a dictionary defined.
  18964. *
  18965. * @param {Object} object - The object to test.
  18966. * @return {boolean} Whether a dictionary is defined or not.
  18967. */
  18968. has( object ) {
  18969. return this.data.has( object );
  18970. }
  18971. /**
  18972. * Frees internal resources.
  18973. */
  18974. dispose() {
  18975. this.data = new WeakMap();
  18976. }
  18977. }
  18978. const AttributeType = {
  18979. VERTEX: 1,
  18980. INDEX: 2,
  18981. STORAGE: 3,
  18982. INDIRECT: 4
  18983. };
  18984. // size of a chunk in bytes (STD140 layout)
  18985. const GPU_CHUNK_BYTES = 16;
  18986. // @TODO: Move to src/constants.js
  18987. const BlendColorFactor = 211;
  18988. const OneMinusBlendColorFactor = 212;
  18989. /**
  18990. * This renderer module manages geometry attributes.
  18991. *
  18992. * @private
  18993. * @augments DataMap
  18994. */
  18995. class Attributes extends DataMap {
  18996. /**
  18997. * Constructs a new attribute management component.
  18998. *
  18999. * @param {Backend} backend - The renderer's backend.
  19000. */
  19001. constructor( backend ) {
  19002. super();
  19003. /**
  19004. * The renderer's backend.
  19005. *
  19006. * @type {Backend}
  19007. */
  19008. this.backend = backend;
  19009. }
  19010. /**
  19011. * Deletes the data for the given attribute.
  19012. *
  19013. * @param {BufferAttribute} attribute - The attribute.
  19014. * @return {Object|null} The deleted attribute data.
  19015. */
  19016. delete( attribute ) {
  19017. const attributeData = super.delete( attribute );
  19018. if ( attributeData !== null ) {
  19019. this.backend.destroyAttribute( attribute );
  19020. }
  19021. return attributeData;
  19022. }
  19023. /**
  19024. * Updates the given attribute. This method creates attribute buffers
  19025. * for new attributes and updates data for existing ones.
  19026. *
  19027. * @param {BufferAttribute} attribute - The attribute to update.
  19028. * @param {number} type - The attribute type.
  19029. */
  19030. update( attribute, type ) {
  19031. const data = this.get( attribute );
  19032. if ( data.version === undefined ) {
  19033. if ( type === AttributeType.VERTEX ) {
  19034. this.backend.createAttribute( attribute );
  19035. } else if ( type === AttributeType.INDEX ) {
  19036. this.backend.createIndexAttribute( attribute );
  19037. } else if ( type === AttributeType.STORAGE ) {
  19038. this.backend.createStorageAttribute( attribute );
  19039. } else if ( type === AttributeType.INDIRECT ) {
  19040. this.backend.createIndirectStorageAttribute( attribute );
  19041. }
  19042. data.version = this._getBufferAttribute( attribute ).version;
  19043. } else {
  19044. const bufferAttribute = this._getBufferAttribute( attribute );
  19045. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  19046. this.backend.updateAttribute( attribute );
  19047. data.version = bufferAttribute.version;
  19048. }
  19049. }
  19050. }
  19051. /**
  19052. * Utility method for handling interleaved buffer attributes correctly.
  19053. * To process them, their `InterleavedBuffer` is returned.
  19054. *
  19055. * @param {BufferAttribute} attribute - The attribute.
  19056. * @return {BufferAttribute|InterleavedBuffer}
  19057. */
  19058. _getBufferAttribute( attribute ) {
  19059. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  19060. return attribute;
  19061. }
  19062. }
  19063. /**
  19064. * Returns the wireframe version for the given geometry.
  19065. *
  19066. * @private
  19067. * @function
  19068. * @param {BufferGeometry} geometry - The geometry.
  19069. * @return {number} The version.
  19070. */
  19071. function getWireframeVersion( geometry ) {
  19072. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  19073. }
  19074. /**
  19075. * Returns a wireframe index attribute for the given geometry.
  19076. *
  19077. * @private
  19078. * @function
  19079. * @param {BufferGeometry} geometry - The geometry.
  19080. * @return {BufferAttribute} The wireframe index attribute.
  19081. */
  19082. function getWireframeIndex( geometry ) {
  19083. const indices = [];
  19084. const geometryIndex = geometry.index;
  19085. const geometryPosition = geometry.attributes.position;
  19086. if ( geometryIndex !== null ) {
  19087. const array = geometryIndex.array;
  19088. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  19089. const a = array[ i + 0 ];
  19090. const b = array[ i + 1 ];
  19091. const c = array[ i + 2 ];
  19092. indices.push( a, b, b, c, c, a );
  19093. }
  19094. } else {
  19095. const array = geometryPosition.array;
  19096. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  19097. const a = i + 0;
  19098. const b = i + 1;
  19099. const c = i + 2;
  19100. indices.push( a, b, b, c, c, a );
  19101. }
  19102. }
  19103. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  19104. attribute.version = getWireframeVersion( geometry );
  19105. return attribute;
  19106. }
  19107. /**
  19108. * This renderer module manages geometries.
  19109. *
  19110. * @private
  19111. * @augments DataMap
  19112. */
  19113. class Geometries extends DataMap {
  19114. /**
  19115. * Constructs a new geometry management component.
  19116. *
  19117. * @param {Attributes} attributes - Renderer component for managing attributes.
  19118. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19119. */
  19120. constructor( attributes, info ) {
  19121. super();
  19122. /**
  19123. * Renderer component for managing attributes.
  19124. *
  19125. * @type {Attributes}
  19126. */
  19127. this.attributes = attributes;
  19128. /**
  19129. * Renderer component for managing metrics and monitoring data.
  19130. *
  19131. * @type {Info}
  19132. */
  19133. this.info = info;
  19134. /**
  19135. * Weak Map for managing attributes for wireframe rendering.
  19136. *
  19137. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  19138. */
  19139. this.wireframes = new WeakMap();
  19140. /**
  19141. * This Weak Map is used to make sure buffer attributes are
  19142. * updated only once per render call.
  19143. *
  19144. * @type {WeakMap<BufferAttribute,number>}
  19145. */
  19146. this.attributeCall = new WeakMap();
  19147. }
  19148. /**
  19149. * Returns `true` if the given render object has an initialized geometry.
  19150. *
  19151. * @param {RenderObject} renderObject - The render object.
  19152. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  19153. */
  19154. has( renderObject ) {
  19155. const geometry = renderObject.geometry;
  19156. return super.has( geometry ) && this.get( geometry ).initialized === true;
  19157. }
  19158. /**
  19159. * Prepares the geometry of the given render object for rendering.
  19160. *
  19161. * @param {RenderObject} renderObject - The render object.
  19162. */
  19163. updateForRender( renderObject ) {
  19164. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  19165. this.updateAttributes( renderObject );
  19166. }
  19167. /**
  19168. * Initializes the geometry of the given render object.
  19169. *
  19170. * @param {RenderObject} renderObject - The render object.
  19171. */
  19172. initGeometry( renderObject ) {
  19173. const geometry = renderObject.geometry;
  19174. const geometryData = this.get( geometry );
  19175. geometryData.initialized = true;
  19176. this.info.memory.geometries ++;
  19177. const onDispose = () => {
  19178. this.info.memory.geometries --;
  19179. const index = geometry.index;
  19180. const geometryAttributes = renderObject.getAttributes();
  19181. if ( index !== null ) {
  19182. this.attributes.delete( index );
  19183. }
  19184. for ( const geometryAttribute of geometryAttributes ) {
  19185. this.attributes.delete( geometryAttribute );
  19186. }
  19187. const wireframeAttribute = this.wireframes.get( geometry );
  19188. if ( wireframeAttribute !== undefined ) {
  19189. this.attributes.delete( wireframeAttribute );
  19190. }
  19191. geometry.removeEventListener( 'dispose', onDispose );
  19192. };
  19193. geometry.addEventListener( 'dispose', onDispose );
  19194. }
  19195. /**
  19196. * Updates the geometry attributes of the given render object.
  19197. *
  19198. * @param {RenderObject} renderObject - The render object.
  19199. */
  19200. updateAttributes( renderObject ) {
  19201. // attributes
  19202. const attributes = renderObject.getAttributes();
  19203. for ( const attribute of attributes ) {
  19204. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  19205. this.updateAttribute( attribute, AttributeType.STORAGE );
  19206. } else {
  19207. this.updateAttribute( attribute, AttributeType.VERTEX );
  19208. }
  19209. }
  19210. // indexes
  19211. const index = this.getIndex( renderObject );
  19212. if ( index !== null ) {
  19213. this.updateAttribute( index, AttributeType.INDEX );
  19214. }
  19215. // indirect
  19216. const indirect = renderObject.geometry.indirect;
  19217. if ( indirect !== null ) {
  19218. this.updateAttribute( indirect, AttributeType.INDIRECT );
  19219. }
  19220. }
  19221. /**
  19222. * Updates the given attribute.
  19223. *
  19224. * @param {BufferAttribute} attribute - The attribute to update.
  19225. * @param {number} type - The attribute type.
  19226. */
  19227. updateAttribute( attribute, type ) {
  19228. const callId = this.info.render.calls;
  19229. if ( ! attribute.isInterleavedBufferAttribute ) {
  19230. if ( this.attributeCall.get( attribute ) !== callId ) {
  19231. this.attributes.update( attribute, type );
  19232. this.attributeCall.set( attribute, callId );
  19233. }
  19234. } else {
  19235. if ( this.attributeCall.get( attribute ) === undefined ) {
  19236. this.attributes.update( attribute, type );
  19237. this.attributeCall.set( attribute, callId );
  19238. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  19239. this.attributes.update( attribute, type );
  19240. this.attributeCall.set( attribute.data, callId );
  19241. this.attributeCall.set( attribute, callId );
  19242. }
  19243. }
  19244. }
  19245. /**
  19246. * Returns the indirect buffer attribute of the given render object.
  19247. *
  19248. * @param {RenderObject} renderObject - The render object.
  19249. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19250. */
  19251. getIndirect( renderObject ) {
  19252. return renderObject.geometry.indirect;
  19253. }
  19254. /**
  19255. * Returns the index of the given render object's geometry. This is implemented
  19256. * in a method to return a wireframe index if necessary.
  19257. *
  19258. * @param {RenderObject} renderObject - The render object.
  19259. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19260. */
  19261. getIndex( renderObject ) {
  19262. const { geometry, material } = renderObject;
  19263. let index = geometry.index;
  19264. if ( material.wireframe === true ) {
  19265. const wireframes = this.wireframes;
  19266. let wireframeAttribute = wireframes.get( geometry );
  19267. if ( wireframeAttribute === undefined ) {
  19268. wireframeAttribute = getWireframeIndex( geometry );
  19269. wireframes.set( geometry, wireframeAttribute );
  19270. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  19271. this.attributes.delete( wireframeAttribute );
  19272. wireframeAttribute = getWireframeIndex( geometry );
  19273. wireframes.set( geometry, wireframeAttribute );
  19274. }
  19275. index = wireframeAttribute;
  19276. }
  19277. return index;
  19278. }
  19279. }
  19280. /**
  19281. * This renderer module provides a series of statistical information
  19282. * about the GPU memory and the rendering process. Useful for debugging
  19283. * and monitoring.
  19284. */
  19285. class Info {
  19286. /**
  19287. * Constructs a new info component.
  19288. */
  19289. constructor() {
  19290. /**
  19291. * Whether frame related metrics should automatically
  19292. * be resetted or not. This property should be set to `false`
  19293. * by apps which manage their own animation loop. They must
  19294. * then call `renderer.info.reset()` once per frame manually.
  19295. *
  19296. * @type {boolean}
  19297. * @default true
  19298. */
  19299. this.autoReset = true;
  19300. /**
  19301. * The current frame ID. This ID is managed
  19302. * by `NodeFrame`.
  19303. *
  19304. * @type {number}
  19305. * @readonly
  19306. * @default 0
  19307. */
  19308. this.frame = 0;
  19309. /**
  19310. * The number of render calls since the
  19311. * app has been started.
  19312. *
  19313. * @type {number}
  19314. * @readonly
  19315. * @default 0
  19316. */
  19317. this.calls = 0;
  19318. /**
  19319. * Render related metrics.
  19320. *
  19321. * @type {Object}
  19322. * @readonly
  19323. * @property {number} calls - The number of render calls since the app has been started.
  19324. * @property {number} frameCalls - The number of render calls of the current frame.
  19325. * @property {number} drawCalls - The number of draw calls of the current frame.
  19326. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  19327. * @property {number} points - The number of rendered point primitives of the current frame.
  19328. * @property {number} lines - The number of rendered line primitives of the current frame.
  19329. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  19330. */
  19331. this.render = {
  19332. calls: 0,
  19333. frameCalls: 0,
  19334. drawCalls: 0,
  19335. triangles: 0,
  19336. points: 0,
  19337. lines: 0,
  19338. timestamp: 0,
  19339. };
  19340. /**
  19341. * Compute related metrics.
  19342. *
  19343. * @type {Object}
  19344. * @readonly
  19345. * @property {number} calls - The number of compute calls since the app has been started.
  19346. * @property {number} frameCalls - The number of compute calls of the current frame.
  19347. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  19348. */
  19349. this.compute = {
  19350. calls: 0,
  19351. frameCalls: 0,
  19352. timestamp: 0
  19353. };
  19354. /**
  19355. * Memory related metrics.
  19356. *
  19357. * @type {Object}
  19358. * @readonly
  19359. * @property {number} geometries - The number of active geometries.
  19360. * @property {number} frameCalls - The number of active textures.
  19361. */
  19362. this.memory = {
  19363. geometries: 0,
  19364. textures: 0
  19365. };
  19366. }
  19367. /**
  19368. * This method should be executed per draw call and updates the corresponding metrics.
  19369. *
  19370. * @param {Object3D} object - The 3D object that is going to be rendered.
  19371. * @param {number} count - The vertex or index count.
  19372. * @param {number} instanceCount - The instance count.
  19373. */
  19374. update( object, count, instanceCount ) {
  19375. this.render.drawCalls ++;
  19376. if ( object.isMesh || object.isSprite ) {
  19377. this.render.triangles += instanceCount * ( count / 3 );
  19378. } else if ( object.isPoints ) {
  19379. this.render.points += instanceCount * count;
  19380. } else if ( object.isLineSegments ) {
  19381. this.render.lines += instanceCount * ( count / 2 );
  19382. } else if ( object.isLine ) {
  19383. this.render.lines += instanceCount * ( count - 1 );
  19384. } else {
  19385. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  19386. }
  19387. }
  19388. /**
  19389. * Resets frame related metrics.
  19390. */
  19391. reset() {
  19392. this.render.drawCalls = 0;
  19393. this.render.frameCalls = 0;
  19394. this.compute.frameCalls = 0;
  19395. this.render.triangles = 0;
  19396. this.render.points = 0;
  19397. this.render.lines = 0;
  19398. }
  19399. /**
  19400. * Performs a complete reset of the object.
  19401. */
  19402. dispose() {
  19403. this.reset();
  19404. this.calls = 0;
  19405. this.render.calls = 0;
  19406. this.compute.calls = 0;
  19407. this.render.timestamp = 0;
  19408. this.compute.timestamp = 0;
  19409. this.memory.geometries = 0;
  19410. this.memory.textures = 0;
  19411. }
  19412. }
  19413. /**
  19414. * Abstract class for representing pipelines.
  19415. *
  19416. * @private
  19417. * @abstract
  19418. */
  19419. class Pipeline {
  19420. /**
  19421. * Constructs a new pipeline.
  19422. *
  19423. * @param {string} cacheKey - The pipeline's cache key.
  19424. */
  19425. constructor( cacheKey ) {
  19426. /**
  19427. * The pipeline's cache key.
  19428. *
  19429. * @type {string}
  19430. */
  19431. this.cacheKey = cacheKey;
  19432. /**
  19433. * How often the pipeline is currently in use.
  19434. *
  19435. * @type {number}
  19436. * @default 0
  19437. */
  19438. this.usedTimes = 0;
  19439. }
  19440. }
  19441. /**
  19442. * Class for representing render pipelines.
  19443. *
  19444. * @private
  19445. * @augments Pipeline
  19446. */
  19447. class RenderPipeline extends Pipeline {
  19448. /**
  19449. * Constructs a new render pipeline.
  19450. *
  19451. * @param {string} cacheKey - The pipeline's cache key.
  19452. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  19453. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  19454. */
  19455. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  19456. super( cacheKey );
  19457. /**
  19458. * The pipeline's vertex shader.
  19459. *
  19460. * @type {ProgrammableStage}
  19461. */
  19462. this.vertexProgram = vertexProgram;
  19463. /**
  19464. * The pipeline's fragment shader.
  19465. *
  19466. * @type {ProgrammableStage}
  19467. */
  19468. this.fragmentProgram = fragmentProgram;
  19469. }
  19470. }
  19471. /**
  19472. * Class for representing compute pipelines.
  19473. *
  19474. * @private
  19475. * @augments Pipeline
  19476. */
  19477. class ComputePipeline extends Pipeline {
  19478. /**
  19479. * Constructs a new render pipeline.
  19480. *
  19481. * @param {string} cacheKey - The pipeline's cache key.
  19482. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  19483. */
  19484. constructor( cacheKey, computeProgram ) {
  19485. super( cacheKey );
  19486. /**
  19487. * The pipeline's compute shader.
  19488. *
  19489. * @type {ProgrammableStage}
  19490. */
  19491. this.computeProgram = computeProgram;
  19492. /**
  19493. * This flag can be used for type testing.
  19494. *
  19495. * @type {boolean}
  19496. * @readonly
  19497. * @default true
  19498. */
  19499. this.isComputePipeline = true;
  19500. }
  19501. }
  19502. let _id$8 = 0;
  19503. /**
  19504. * Class for representing programmable stages which are vertex,
  19505. * fragment or compute shaders. Unlike fixed-function states (like blending),
  19506. * they represent the programmable part of a pipeline.
  19507. *
  19508. * @private
  19509. */
  19510. class ProgrammableStage {
  19511. /**
  19512. * Constructs a new programmable stage.
  19513. *
  19514. * @param {string} code - The shader code.
  19515. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  19516. * @param {string} name - The name of the shader.
  19517. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19518. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19519. */
  19520. constructor( code, stage, name, transforms = null, attributes = null ) {
  19521. /**
  19522. * The id of the programmable stage.
  19523. *
  19524. * @type {number}
  19525. */
  19526. this.id = _id$8 ++;
  19527. /**
  19528. * The shader code.
  19529. *
  19530. * @type {string}
  19531. */
  19532. this.code = code;
  19533. /**
  19534. * The type of stage.
  19535. *
  19536. * @type {string}
  19537. */
  19538. this.stage = stage;
  19539. /**
  19540. * The name of the stage.
  19541. * This is used for debugging purposes.
  19542. *
  19543. * @type {string}
  19544. */
  19545. this.name = name;
  19546. /**
  19547. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19548. *
  19549. * @type {?Array<Object>}
  19550. */
  19551. this.transforms = transforms;
  19552. /**
  19553. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19554. *
  19555. * @type {?Array<Object>}
  19556. */
  19557. this.attributes = attributes;
  19558. /**
  19559. * How often the programmable stage is currently in use.
  19560. *
  19561. * @type {number}
  19562. * @default 0
  19563. */
  19564. this.usedTimes = 0;
  19565. }
  19566. }
  19567. /**
  19568. * This renderer module manages the pipelines of the renderer.
  19569. *
  19570. * @private
  19571. * @augments DataMap
  19572. */
  19573. class Pipelines extends DataMap {
  19574. /**
  19575. * Constructs a new pipeline management component.
  19576. *
  19577. * @param {Backend} backend - The renderer's backend.
  19578. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19579. */
  19580. constructor( backend, nodes ) {
  19581. super();
  19582. /**
  19583. * The renderer's backend.
  19584. *
  19585. * @type {Backend}
  19586. */
  19587. this.backend = backend;
  19588. /**
  19589. * Renderer component for managing nodes related logic.
  19590. *
  19591. * @type {Nodes}
  19592. */
  19593. this.nodes = nodes;
  19594. /**
  19595. * A references to the bindings management component.
  19596. * This reference will be set inside the `Bindings`
  19597. * constructor.
  19598. *
  19599. * @type {?Bindings}
  19600. * @default null
  19601. */
  19602. this.bindings = null;
  19603. /**
  19604. * Internal cache for maintaining pipelines.
  19605. * The key of the map is a cache key, the value the pipeline.
  19606. *
  19607. * @type {Map<string,Pipeline>}
  19608. */
  19609. this.caches = new Map();
  19610. /**
  19611. * This dictionary maintains for each shader stage type (vertex,
  19612. * fragment and compute) the programmable stage objects which
  19613. * represent the actual shader code.
  19614. *
  19615. * @type {Object<string,Map>}
  19616. */
  19617. this.programs = {
  19618. vertex: new Map(),
  19619. fragment: new Map(),
  19620. compute: new Map()
  19621. };
  19622. }
  19623. /**
  19624. * Returns a compute pipeline for the given compute node.
  19625. *
  19626. * @param {Node} computeNode - The compute node.
  19627. * @param {Array<BindGroup>} bindings - The bindings.
  19628. * @return {ComputePipeline} The compute pipeline.
  19629. */
  19630. getForCompute( computeNode, bindings ) {
  19631. const { backend } = this;
  19632. const data = this.get( computeNode );
  19633. if ( this._needsComputeUpdate( computeNode ) ) {
  19634. const previousPipeline = data.pipeline;
  19635. if ( previousPipeline ) {
  19636. previousPipeline.usedTimes --;
  19637. previousPipeline.computeProgram.usedTimes --;
  19638. }
  19639. // get shader
  19640. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  19641. // programmable stage
  19642. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  19643. if ( stageCompute === undefined ) {
  19644. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  19645. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  19646. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  19647. backend.createProgram( stageCompute );
  19648. }
  19649. // determine compute pipeline
  19650. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  19651. let pipeline = this.caches.get( cacheKey );
  19652. if ( pipeline === undefined ) {
  19653. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  19654. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  19655. }
  19656. // keep track of all used times
  19657. pipeline.usedTimes ++;
  19658. stageCompute.usedTimes ++;
  19659. //
  19660. data.version = computeNode.version;
  19661. data.pipeline = pipeline;
  19662. }
  19663. return data.pipeline;
  19664. }
  19665. /**
  19666. * Returns a render pipeline for the given render object.
  19667. *
  19668. * @param {RenderObject} renderObject - The render object.
  19669. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  19670. * @return {RenderPipeline} The render pipeline.
  19671. */
  19672. getForRender( renderObject, promises = null ) {
  19673. const { backend } = this;
  19674. const data = this.get( renderObject );
  19675. if ( this._needsRenderUpdate( renderObject ) ) {
  19676. const previousPipeline = data.pipeline;
  19677. if ( previousPipeline ) {
  19678. previousPipeline.usedTimes --;
  19679. previousPipeline.vertexProgram.usedTimes --;
  19680. previousPipeline.fragmentProgram.usedTimes --;
  19681. }
  19682. // get shader
  19683. const nodeBuilderState = renderObject.getNodeBuilderState();
  19684. const name = renderObject.material ? renderObject.material.name : '';
  19685. // programmable stages
  19686. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  19687. if ( stageVertex === undefined ) {
  19688. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  19689. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  19690. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  19691. backend.createProgram( stageVertex );
  19692. }
  19693. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  19694. if ( stageFragment === undefined ) {
  19695. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  19696. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  19697. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  19698. backend.createProgram( stageFragment );
  19699. }
  19700. // determine render pipeline
  19701. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  19702. let pipeline = this.caches.get( cacheKey );
  19703. if ( pipeline === undefined ) {
  19704. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  19705. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  19706. } else {
  19707. renderObject.pipeline = pipeline;
  19708. }
  19709. // keep track of all used times
  19710. pipeline.usedTimes ++;
  19711. stageVertex.usedTimes ++;
  19712. stageFragment.usedTimes ++;
  19713. //
  19714. data.pipeline = pipeline;
  19715. }
  19716. return data.pipeline;
  19717. }
  19718. /**
  19719. * Deletes the pipeline for the given render object.
  19720. *
  19721. * @param {RenderObject} object - The render object.
  19722. * @return {?Object} The deleted dictionary.
  19723. */
  19724. delete( object ) {
  19725. const pipeline = this.get( object ).pipeline;
  19726. if ( pipeline ) {
  19727. // pipeline
  19728. pipeline.usedTimes --;
  19729. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  19730. // programs
  19731. if ( pipeline.isComputePipeline ) {
  19732. pipeline.computeProgram.usedTimes --;
  19733. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  19734. } else {
  19735. pipeline.fragmentProgram.usedTimes --;
  19736. pipeline.vertexProgram.usedTimes --;
  19737. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  19738. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  19739. }
  19740. }
  19741. return super.delete( object );
  19742. }
  19743. /**
  19744. * Frees internal resources.
  19745. */
  19746. dispose() {
  19747. super.dispose();
  19748. this.caches = new Map();
  19749. this.programs = {
  19750. vertex: new Map(),
  19751. fragment: new Map(),
  19752. compute: new Map()
  19753. };
  19754. }
  19755. /**
  19756. * Updates the pipeline for the given render object.
  19757. *
  19758. * @param {RenderObject} renderObject - The render object.
  19759. */
  19760. updateForRender( renderObject ) {
  19761. this.getForRender( renderObject );
  19762. }
  19763. /**
  19764. * Returns a compute pipeline for the given parameters.
  19765. *
  19766. * @private
  19767. * @param {Node} computeNode - The compute node.
  19768. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  19769. * @param {string} cacheKey - The cache key.
  19770. * @param {Array<BindGroup>} bindings - The bindings.
  19771. * @return {ComputePipeline} The compute pipeline.
  19772. */
  19773. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  19774. // check for existing pipeline
  19775. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  19776. let pipeline = this.caches.get( cacheKey );
  19777. if ( pipeline === undefined ) {
  19778. pipeline = new ComputePipeline( cacheKey, stageCompute );
  19779. this.caches.set( cacheKey, pipeline );
  19780. this.backend.createComputePipeline( pipeline, bindings );
  19781. }
  19782. return pipeline;
  19783. }
  19784. /**
  19785. * Returns a render pipeline for the given parameters.
  19786. *
  19787. * @private
  19788. * @param {RenderObject} renderObject - The render object.
  19789. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  19790. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  19791. * @param {string} cacheKey - The cache key.
  19792. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  19793. * @return {ComputePipeline} The compute pipeline.
  19794. */
  19795. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  19796. // check for existing pipeline
  19797. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  19798. let pipeline = this.caches.get( cacheKey );
  19799. if ( pipeline === undefined ) {
  19800. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  19801. this.caches.set( cacheKey, pipeline );
  19802. renderObject.pipeline = pipeline;
  19803. // The `promises` array is `null` by default and only set to an empty array when
  19804. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  19805. // pending promises that resolve when the render pipelines are ready for rendering.
  19806. this.backend.createRenderPipeline( renderObject, promises );
  19807. }
  19808. return pipeline;
  19809. }
  19810. /**
  19811. * Computes a cache key representing a compute pipeline.
  19812. *
  19813. * @private
  19814. * @param {Node} computeNode - The compute node.
  19815. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  19816. * @return {string} The cache key.
  19817. */
  19818. _getComputeCacheKey( computeNode, stageCompute ) {
  19819. return computeNode.id + ',' + stageCompute.id;
  19820. }
  19821. /**
  19822. * Computes a cache key representing a render pipeline.
  19823. *
  19824. * @private
  19825. * @param {RenderObject} renderObject - The render object.
  19826. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  19827. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  19828. * @return {string} The cache key.
  19829. */
  19830. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  19831. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  19832. }
  19833. /**
  19834. * Releases the given pipeline.
  19835. *
  19836. * @private
  19837. * @param {Pipeline} pipeline - The pipeline to release.
  19838. */
  19839. _releasePipeline( pipeline ) {
  19840. this.caches.delete( pipeline.cacheKey );
  19841. }
  19842. /**
  19843. * Releases the shader program.
  19844. *
  19845. * @private
  19846. * @param {Object} program - The shader program to release.
  19847. */
  19848. _releaseProgram( program ) {
  19849. const code = program.code;
  19850. const stage = program.stage;
  19851. this.programs[ stage ].delete( code );
  19852. }
  19853. /**
  19854. * Returns `true` if the compute pipeline for the given compute node requires an update.
  19855. *
  19856. * @private
  19857. * @param {Node} computeNode - The compute node.
  19858. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  19859. */
  19860. _needsComputeUpdate( computeNode ) {
  19861. const data = this.get( computeNode );
  19862. return data.pipeline === undefined || data.version !== computeNode.version;
  19863. }
  19864. /**
  19865. * Returns `true` if the render pipeline for the given render object requires an update.
  19866. *
  19867. * @private
  19868. * @param {RenderObject} renderObject - The render object.
  19869. * @return {boolean} Whether the render object for the given render object requires an update or not.
  19870. */
  19871. _needsRenderUpdate( renderObject ) {
  19872. const data = this.get( renderObject );
  19873. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  19874. }
  19875. }
  19876. /**
  19877. * This renderer module manages the bindings of the renderer.
  19878. *
  19879. * @private
  19880. * @augments DataMap
  19881. */
  19882. class Bindings extends DataMap {
  19883. /**
  19884. * Constructs a new bindings management component.
  19885. *
  19886. * @param {Backend} backend - The renderer's backend.
  19887. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19888. * @param {Textures} textures - Renderer component for managing textures.
  19889. * @param {Attributes} attributes - Renderer component for managing attributes.
  19890. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19891. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19892. */
  19893. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  19894. super();
  19895. /**
  19896. * The renderer's backend.
  19897. *
  19898. * @type {Backend}
  19899. */
  19900. this.backend = backend;
  19901. /**
  19902. * Renderer component for managing textures.
  19903. *
  19904. * @type {Textures}
  19905. */
  19906. this.textures = textures;
  19907. /**
  19908. * Renderer component for managing pipelines.
  19909. *
  19910. * @type {Pipelines}
  19911. */
  19912. this.pipelines = pipelines;
  19913. /**
  19914. * Renderer component for managing attributes.
  19915. *
  19916. * @type {Attributes}
  19917. */
  19918. this.attributes = attributes;
  19919. /**
  19920. * Renderer component for managing nodes related logic.
  19921. *
  19922. * @type {Nodes}
  19923. */
  19924. this.nodes = nodes;
  19925. /**
  19926. * Renderer component for managing metrics and monitoring data.
  19927. *
  19928. * @type {Info}
  19929. */
  19930. this.info = info;
  19931. this.pipelines.bindings = this; // assign bindings to pipelines
  19932. }
  19933. /**
  19934. * Returns the bind groups for the given render object.
  19935. *
  19936. * @param {RenderObject} renderObject - The render object.
  19937. * @return {Array<BindGroup>} The bind groups.
  19938. */
  19939. getForRender( renderObject ) {
  19940. const bindings = renderObject.getBindings();
  19941. for ( const bindGroup of bindings ) {
  19942. const groupData = this.get( bindGroup );
  19943. if ( groupData.bindGroup === undefined ) {
  19944. // each object defines an array of bindings (ubos, textures, samplers etc.)
  19945. this._init( bindGroup );
  19946. this.backend.createBindings( bindGroup, bindings, 0 );
  19947. groupData.bindGroup = bindGroup;
  19948. }
  19949. }
  19950. return bindings;
  19951. }
  19952. /**
  19953. * Returns the bind groups for the given compute node.
  19954. *
  19955. * @param {Node} computeNode - The compute node.
  19956. * @return {Array<BindGroup>} The bind groups.
  19957. */
  19958. getForCompute( computeNode ) {
  19959. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  19960. for ( const bindGroup of bindings ) {
  19961. const groupData = this.get( bindGroup );
  19962. if ( groupData.bindGroup === undefined ) {
  19963. this._init( bindGroup );
  19964. this.backend.createBindings( bindGroup, bindings, 0 );
  19965. groupData.bindGroup = bindGroup;
  19966. }
  19967. }
  19968. return bindings;
  19969. }
  19970. /**
  19971. * Updates the bindings for the given compute node.
  19972. *
  19973. * @param {Node} computeNode - The compute node.
  19974. */
  19975. updateForCompute( computeNode ) {
  19976. this._updateBindings( this.getForCompute( computeNode ) );
  19977. }
  19978. /**
  19979. * Updates the bindings for the given render object.
  19980. *
  19981. * @param {RenderObject} renderObject - The render object.
  19982. */
  19983. updateForRender( renderObject ) {
  19984. this._updateBindings( this.getForRender( renderObject ) );
  19985. }
  19986. /**
  19987. * Updates the given array of bindings.
  19988. *
  19989. * @param {Array<BindGroup>} bindings - The bind groups.
  19990. */
  19991. _updateBindings( bindings ) {
  19992. for ( const bindGroup of bindings ) {
  19993. this._update( bindGroup, bindings );
  19994. }
  19995. }
  19996. /**
  19997. * Initializes the given bind group.
  19998. *
  19999. * @param {BindGroup} bindGroup - The bind group to initialize.
  20000. */
  20001. _init( bindGroup ) {
  20002. for ( const binding of bindGroup.bindings ) {
  20003. if ( binding.isSampledTexture ) {
  20004. this.textures.updateTexture( binding.texture );
  20005. } else if ( binding.isStorageBuffer ) {
  20006. const attribute = binding.attribute;
  20007. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20008. this.attributes.update( attribute, attributeType );
  20009. }
  20010. }
  20011. }
  20012. /**
  20013. * Updates the given bind group.
  20014. *
  20015. * @param {BindGroup} bindGroup - The bind group to update.
  20016. * @param {Array<BindGroup>} bindings - The bind groups.
  20017. */
  20018. _update( bindGroup, bindings ) {
  20019. const { backend } = this;
  20020. let needsBindingsUpdate = false;
  20021. let cacheBindings = true;
  20022. let cacheIndex = 0;
  20023. let version = 0;
  20024. // iterate over all bindings and check if buffer updates or a new binding group is required
  20025. for ( const binding of bindGroup.bindings ) {
  20026. if ( binding.isNodeUniformsGroup ) {
  20027. const updated = this.nodes.updateGroup( binding );
  20028. // every uniforms group is a uniform buffer. So if no update is required,
  20029. // we move one with the next binding. Otherwise the next if block will update the group.
  20030. if ( updated === false ) continue;
  20031. }
  20032. if ( binding.isStorageBuffer ) {
  20033. const attribute = binding.attribute;
  20034. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20035. this.attributes.update( attribute, attributeType );
  20036. }
  20037. if ( binding.isUniformBuffer ) {
  20038. const updated = binding.update();
  20039. if ( updated ) {
  20040. backend.updateBinding( binding );
  20041. }
  20042. } else if ( binding.isSampler ) {
  20043. binding.update();
  20044. } else if ( binding.isSampledTexture ) {
  20045. const texturesTextureData = this.textures.get( binding.texture );
  20046. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  20047. const updated = binding.update();
  20048. const texture = binding.texture;
  20049. if ( updated ) {
  20050. this.textures.updateTexture( texture );
  20051. }
  20052. const textureData = backend.get( texture );
  20053. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  20054. cacheBindings = false;
  20055. } else {
  20056. cacheIndex = cacheIndex * 10 + texture.id;
  20057. version += texture.version;
  20058. }
  20059. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  20060. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  20061. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  20062. this.textures.updateTexture( texture );
  20063. needsBindingsUpdate = true;
  20064. }
  20065. if ( texture.isStorageTexture === true ) {
  20066. const textureData = this.get( texture );
  20067. if ( binding.store === true ) {
  20068. textureData.needsMipmap = true;
  20069. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  20070. this.backend.generateMipmaps( texture );
  20071. textureData.needsMipmap = false;
  20072. }
  20073. }
  20074. }
  20075. }
  20076. if ( needsBindingsUpdate === true ) {
  20077. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  20078. }
  20079. }
  20080. }
  20081. /**
  20082. * Default sorting function for opaque render items.
  20083. *
  20084. * @private
  20085. * @function
  20086. * @param {Object} a - The first render item.
  20087. * @param {Object} b - The second render item.
  20088. * @return {number} A numeric value which defines the sort order.
  20089. */
  20090. function painterSortStable( a, b ) {
  20091. if ( a.groupOrder !== b.groupOrder ) {
  20092. return a.groupOrder - b.groupOrder;
  20093. } else if ( a.renderOrder !== b.renderOrder ) {
  20094. return a.renderOrder - b.renderOrder;
  20095. } else if ( a.z !== b.z ) {
  20096. return a.z - b.z;
  20097. } else {
  20098. return a.id - b.id;
  20099. }
  20100. }
  20101. /**
  20102. * Default sorting function for transparent render items.
  20103. *
  20104. * @private
  20105. * @function
  20106. * @param {Object} a - The first render item.
  20107. * @param {Object} b - The second render item.
  20108. * @return {number} A numeric value which defines the sort order.
  20109. */
  20110. function reversePainterSortStable( a, b ) {
  20111. if ( a.groupOrder !== b.groupOrder ) {
  20112. return a.groupOrder - b.groupOrder;
  20113. } else if ( a.renderOrder !== b.renderOrder ) {
  20114. return a.renderOrder - b.renderOrder;
  20115. } else if ( a.z !== b.z ) {
  20116. return b.z - a.z;
  20117. } else {
  20118. return a.id - b.id;
  20119. }
  20120. }
  20121. /**
  20122. * Returns `true` if the given transparent material requires a double pass.
  20123. *
  20124. * @private
  20125. * @function
  20126. * @param {Material} material - The transparent material.
  20127. * @return {boolean} Whether the given material requires a double pass or not.
  20128. */
  20129. function needsDoublePass( material ) {
  20130. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  20131. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  20132. }
  20133. /**
  20134. * When the renderer analyzes the scene at the beginning of a render call,
  20135. * it stores 3D object for further processing in render lists. Depending on the
  20136. * properties of a 3D objects (like their transformation or material state), the
  20137. * objects are maintained in ordered lists for the actual rendering.
  20138. *
  20139. * Render lists are unique per scene and camera combination.
  20140. *
  20141. * @private
  20142. * @augments Pipeline
  20143. */
  20144. class RenderList {
  20145. /**
  20146. * Constructs a render list.
  20147. *
  20148. * @param {Lighting} lighting - The lighting management component.
  20149. * @param {Scene} scene - The scene.
  20150. * @param {Camera} camera - The camera the scene is rendered with.
  20151. */
  20152. constructor( lighting, scene, camera ) {
  20153. /**
  20154. * 3D objects are transformed into render items and stored in this array.
  20155. *
  20156. * @type {Array<Object>}
  20157. */
  20158. this.renderItems = [];
  20159. /**
  20160. * The current render items index.
  20161. *
  20162. * @type {number}
  20163. * @default 0
  20164. */
  20165. this.renderItemsIndex = 0;
  20166. /**
  20167. * A list with opaque render items.
  20168. *
  20169. * @type {Array<Object>}
  20170. */
  20171. this.opaque = [];
  20172. /**
  20173. * A list with transparent render items which require
  20174. * double pass rendering (e.g. transmissive objects).
  20175. *
  20176. * @type {Array<Object>}
  20177. */
  20178. this.transparentDoublePass = [];
  20179. /**
  20180. * A list with transparent render items.
  20181. *
  20182. * @type {Array<Object>}
  20183. */
  20184. this.transparent = [];
  20185. /**
  20186. * A list with transparent render bundle data.
  20187. *
  20188. * @type {Array<Object>}
  20189. */
  20190. this.bundles = [];
  20191. /**
  20192. * The render list's lights node. This node is later
  20193. * relevant for the actual analytical light nodes which
  20194. * compute the scene's lighting in the shader.
  20195. *
  20196. * @type {LightsNode}
  20197. */
  20198. this.lightsNode = lighting.getNode( scene, camera );
  20199. /**
  20200. * The scene's lights stored in an array. This array
  20201. * is used to setup the lights node.
  20202. *
  20203. * @type {Array<Light>}
  20204. */
  20205. this.lightsArray = [];
  20206. /**
  20207. * The scene.
  20208. *
  20209. * @type {Scene}
  20210. */
  20211. this.scene = scene;
  20212. /**
  20213. * The camera the scene is rendered with.
  20214. *
  20215. * @type {Camera}
  20216. */
  20217. this.camera = camera;
  20218. /**
  20219. * How many objects perform occlusion query tests.
  20220. *
  20221. * @type {number}
  20222. * @default 0
  20223. */
  20224. this.occlusionQueryCount = 0;
  20225. }
  20226. /**
  20227. * This method is called right at the beginning of a render call
  20228. * before the scene is analyzed. It prepares the internal data
  20229. * structures for the upcoming render lists generation.
  20230. *
  20231. * @return {RenderList} A reference to this render list.
  20232. */
  20233. begin() {
  20234. this.renderItemsIndex = 0;
  20235. this.opaque.length = 0;
  20236. this.transparentDoublePass.length = 0;
  20237. this.transparent.length = 0;
  20238. this.bundles.length = 0;
  20239. this.lightsArray.length = 0;
  20240. this.occlusionQueryCount = 0;
  20241. return this;
  20242. }
  20243. /**
  20244. * Returns a render item for the giving render item state. The state is defined
  20245. * by a series of object-related parameters.
  20246. *
  20247. * The method avoids object creation by holding render items and reusing them in
  20248. * subsequent render calls (just with different property values).
  20249. *
  20250. * @param {Object3D} object - The 3D object.
  20251. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20252. * @param {Material} material - The 3D object's material.
  20253. * @param {number} groupOrder - The current group order.
  20254. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20255. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20256. * @param {ClippingContext} clippingContext - The current clipping context.
  20257. * @return {Object} The render item.
  20258. */
  20259. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20260. let renderItem = this.renderItems[ this.renderItemsIndex ];
  20261. if ( renderItem === undefined ) {
  20262. renderItem = {
  20263. id: object.id,
  20264. object: object,
  20265. geometry: geometry,
  20266. material: material,
  20267. groupOrder: groupOrder,
  20268. renderOrder: object.renderOrder,
  20269. z: z,
  20270. group: group,
  20271. clippingContext: clippingContext
  20272. };
  20273. this.renderItems[ this.renderItemsIndex ] = renderItem;
  20274. } else {
  20275. renderItem.id = object.id;
  20276. renderItem.object = object;
  20277. renderItem.geometry = geometry;
  20278. renderItem.material = material;
  20279. renderItem.groupOrder = groupOrder;
  20280. renderItem.renderOrder = object.renderOrder;
  20281. renderItem.z = z;
  20282. renderItem.group = group;
  20283. renderItem.clippingContext = clippingContext;
  20284. }
  20285. this.renderItemsIndex ++;
  20286. return renderItem;
  20287. }
  20288. /**
  20289. * Pushes the given object as a render item to the internal render lists.
  20290. * The selected lists depend on the object properties.
  20291. *
  20292. * @param {Object3D} object - The 3D object.
  20293. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20294. * @param {Material} material - The 3D object's material.
  20295. * @param {number} groupOrder - The current group order.
  20296. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20297. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20298. * @param {ClippingContext} clippingContext - The current clipping context.
  20299. */
  20300. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20301. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20302. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  20303. if ( material.transparent === true || material.transmission > 0 ) {
  20304. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  20305. this.transparent.push( renderItem );
  20306. } else {
  20307. this.opaque.push( renderItem );
  20308. }
  20309. }
  20310. /**
  20311. * Inserts the given object as a render item at the start of the internal render lists.
  20312. * The selected lists depend on the object properties.
  20313. *
  20314. * @param {Object3D} object - The 3D object.
  20315. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20316. * @param {Material} material - The 3D object's material.
  20317. * @param {number} groupOrder - The current group order.
  20318. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20319. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20320. * @param {ClippingContext} clippingContext - The current clipping context.
  20321. */
  20322. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20323. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20324. if ( material.transparent === true || material.transmission > 0 ) {
  20325. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  20326. this.transparent.unshift( renderItem );
  20327. } else {
  20328. this.opaque.unshift( renderItem );
  20329. }
  20330. }
  20331. /**
  20332. * Pushes render bundle group data into the render list.
  20333. *
  20334. * @param {Object} group - Bundle group data.
  20335. */
  20336. pushBundle( group ) {
  20337. this.bundles.push( group );
  20338. }
  20339. /**
  20340. * Pushes a light into the render list.
  20341. *
  20342. * @param {Light} light - The light.
  20343. */
  20344. pushLight( light ) {
  20345. this.lightsArray.push( light );
  20346. }
  20347. /**
  20348. * Sorts the internal render lists.
  20349. *
  20350. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  20351. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  20352. */
  20353. sort( customOpaqueSort, customTransparentSort ) {
  20354. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  20355. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  20356. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  20357. }
  20358. /**
  20359. * This method performs finalizing tasks right after the render lists
  20360. * have been generated.
  20361. */
  20362. finish() {
  20363. // update lights
  20364. this.lightsNode.setLights( this.lightsArray );
  20365. // Clear references from inactive renderItems in the list
  20366. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  20367. const renderItem = this.renderItems[ i ];
  20368. if ( renderItem.id === null ) break;
  20369. renderItem.id = null;
  20370. renderItem.object = null;
  20371. renderItem.geometry = null;
  20372. renderItem.material = null;
  20373. renderItem.groupOrder = null;
  20374. renderItem.renderOrder = null;
  20375. renderItem.z = null;
  20376. renderItem.group = null;
  20377. renderItem.clippingContext = null;
  20378. }
  20379. }
  20380. }
  20381. const _chainKeys$4 = [];
  20382. /**
  20383. * This renderer module manages the render lists which are unique
  20384. * per scene and camera combination.
  20385. *
  20386. * @private
  20387. */
  20388. class RenderLists {
  20389. /**
  20390. * Constructs a render lists management component.
  20391. *
  20392. * @param {Lighting} lighting - The lighting management component.
  20393. */
  20394. constructor( lighting ) {
  20395. /**
  20396. * The lighting management component.
  20397. *
  20398. * @type {Lighting}
  20399. */
  20400. this.lighting = lighting;
  20401. /**
  20402. * The internal chain map which holds the render lists.
  20403. *
  20404. * @type {ChainMap}
  20405. */
  20406. this.lists = new ChainMap();
  20407. }
  20408. /**
  20409. * Returns a render list for the given scene and camera.
  20410. *
  20411. * @param {Scene} scene - The scene.
  20412. * @param {Camera} camera - The camera.
  20413. * @return {RenderList} The render list.
  20414. */
  20415. get( scene, camera ) {
  20416. const lists = this.lists;
  20417. _chainKeys$4[ 0 ] = scene;
  20418. _chainKeys$4[ 1 ] = camera;
  20419. let list = lists.get( _chainKeys$4 );
  20420. if ( list === undefined ) {
  20421. list = new RenderList( this.lighting, scene, camera );
  20422. lists.set( _chainKeys$4, list );
  20423. }
  20424. _chainKeys$4.length = 0;
  20425. return list;
  20426. }
  20427. /**
  20428. * Frees all internal resources.
  20429. */
  20430. dispose() {
  20431. this.lists = new ChainMap();
  20432. }
  20433. }
  20434. let _id$7 = 0;
  20435. /**
  20436. * Any render or compute command is executed in a specific context that defines
  20437. * the state of the renderer and its backend. Typical examples for such context
  20438. * data are the current clear values or data from the active framebuffer. This
  20439. * module is used to represent these contexts as objects.
  20440. *
  20441. * @private
  20442. */
  20443. class RenderContext {
  20444. /**
  20445. * Constructs a new render context.
  20446. */
  20447. constructor() {
  20448. /**
  20449. * The context's ID.
  20450. *
  20451. * @type {number}
  20452. */
  20453. this.id = _id$7 ++;
  20454. /**
  20455. * Whether the current active framebuffer has a color attachment.
  20456. *
  20457. * @type {boolean}
  20458. * @default true
  20459. */
  20460. this.color = true;
  20461. /**
  20462. * Whether the color attachment should be cleared or not.
  20463. *
  20464. * @type {boolean}
  20465. * @default true
  20466. */
  20467. this.clearColor = true;
  20468. /**
  20469. * The clear color value.
  20470. *
  20471. * @type {Object}
  20472. * @default true
  20473. */
  20474. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  20475. /**
  20476. * Whether the current active framebuffer has a depth attachment.
  20477. *
  20478. * @type {boolean}
  20479. * @default true
  20480. */
  20481. this.depth = true;
  20482. /**
  20483. * Whether the depth attachment should be cleared or not.
  20484. *
  20485. * @type {boolean}
  20486. * @default true
  20487. */
  20488. this.clearDepth = true;
  20489. /**
  20490. * The clear depth value.
  20491. *
  20492. * @type {number}
  20493. * @default 1
  20494. */
  20495. this.clearDepthValue = 1;
  20496. /**
  20497. * Whether the current active framebuffer has a stencil attachment.
  20498. *
  20499. * @type {boolean}
  20500. * @default false
  20501. */
  20502. this.stencil = false;
  20503. /**
  20504. * Whether the stencil attachment should be cleared or not.
  20505. *
  20506. * @type {boolean}
  20507. * @default true
  20508. */
  20509. this.clearStencil = true;
  20510. /**
  20511. * The clear stencil value.
  20512. *
  20513. * @type {number}
  20514. * @default 1
  20515. */
  20516. this.clearStencilValue = 1;
  20517. /**
  20518. * By default the viewport encloses the entire framebuffer If a smaller
  20519. * viewport is manually defined, this property is to `true` by the renderer.
  20520. *
  20521. * @type {boolean}
  20522. * @default false
  20523. */
  20524. this.viewport = false;
  20525. /**
  20526. * The viewport value. This value is in physical pixels meaning it incorporates
  20527. * the renderer's pixel ratio. The viewport property of render targets or
  20528. * the renderer is in logical pixels.
  20529. *
  20530. * @type {Vector4}
  20531. */
  20532. this.viewportValue = new Vector4();
  20533. /**
  20534. * When the scissor test is active and scissor rectangle smaller than the
  20535. * framebuffers dimensions, this property is to `true` by the renderer.
  20536. *
  20537. * @type {boolean}
  20538. * @default false
  20539. */
  20540. this.scissor = false;
  20541. /**
  20542. * The scissor rectangle.
  20543. *
  20544. * @type {Vector4}
  20545. */
  20546. this.scissorValue = new Vector4();
  20547. /**
  20548. * The active render target.
  20549. *
  20550. * @type {?RenderTarget}
  20551. * @default null
  20552. */
  20553. this.renderTarget = null;
  20554. /**
  20555. * The textures of the active render target.
  20556. * `null` when no render target is set.
  20557. *
  20558. * @type {?Array<Texture>}
  20559. * @default null
  20560. */
  20561. this.textures = null;
  20562. /**
  20563. * The depth texture of the active render target.
  20564. * `null` when no render target is set.
  20565. *
  20566. * @type {?DepthTexture}
  20567. * @default null
  20568. */
  20569. this.depthTexture = null;
  20570. /**
  20571. * The active cube face.
  20572. *
  20573. * @type {number}
  20574. * @default 0
  20575. */
  20576. this.activeCubeFace = 0;
  20577. /**
  20578. * The active mipmap level.
  20579. *
  20580. * @type {number}
  20581. * @default 0
  20582. */
  20583. this.activeMipmapLevel = 0;
  20584. /**
  20585. * The number of MSAA samples. This value is always `1` when
  20586. * MSAA isn't used.
  20587. *
  20588. * @type {number}
  20589. * @default 1
  20590. */
  20591. this.sampleCount = 1;
  20592. /**
  20593. * The active render target's width in physical pixels.
  20594. *
  20595. * @type {number}
  20596. * @default 0
  20597. */
  20598. this.width = 0;
  20599. /**
  20600. * The active render target's height in physical pixels.
  20601. *
  20602. * @type {number}
  20603. * @default 0
  20604. */
  20605. this.height = 0;
  20606. /**
  20607. * The occlusion query count.
  20608. *
  20609. * @type {number}
  20610. * @default 0
  20611. */
  20612. this.occlusionQueryCount = 0;
  20613. /**
  20614. * The current clipping context.
  20615. *
  20616. * @type {?ClippingContext}
  20617. * @default null
  20618. */
  20619. this.clippingContext = null;
  20620. /**
  20621. * This flag can be used for type testing.
  20622. *
  20623. * @type {boolean}
  20624. * @readonly
  20625. * @default true
  20626. */
  20627. this.isRenderContext = true;
  20628. }
  20629. /**
  20630. * Returns the cache key of this render context.
  20631. *
  20632. * @return {number} The cache key.
  20633. */
  20634. getCacheKey() {
  20635. return getCacheKey( this );
  20636. }
  20637. }
  20638. /**
  20639. * Computes a cache key for the given render context. This key
  20640. * should identify the render target state so it is possible to
  20641. * configure the correct attachments in the respective backend.
  20642. *
  20643. * @param {RenderContext} renderContext - The render context.
  20644. * @return {number} The cache key.
  20645. */
  20646. function getCacheKey( renderContext ) {
  20647. const { textures, activeCubeFace } = renderContext;
  20648. const values = [ activeCubeFace ];
  20649. for ( const texture of textures ) {
  20650. values.push( texture.id );
  20651. }
  20652. return hashArray( values );
  20653. }
  20654. const _chainKeys$3 = [];
  20655. const _defaultScene = /*@__PURE__*/ new Scene();
  20656. const _defaultCamera = /*@__PURE__*/ new Camera();
  20657. /**
  20658. * This module manages the render contexts of the renderer.
  20659. *
  20660. * @private
  20661. */
  20662. class RenderContexts {
  20663. /**
  20664. * Constructs a new render context management component.
  20665. */
  20666. constructor() {
  20667. /**
  20668. * A dictionary that manages render contexts in chain maps
  20669. * for each attachment state.
  20670. *
  20671. * @type {Object<string,ChainMap>}
  20672. */
  20673. this.chainMaps = {};
  20674. }
  20675. /**
  20676. * Returns a render context for the given scene, camera and render target.
  20677. *
  20678. * @param {Scene} scene - The scene.
  20679. * @param {Camera} camera - The camera that is used to render the scene.
  20680. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  20681. * @return {RenderContext} The render context.
  20682. */
  20683. get( scene, camera, renderTarget = null ) {
  20684. _chainKeys$3[ 0 ] = scene;
  20685. _chainKeys$3[ 1 ] = camera;
  20686. let attachmentState;
  20687. if ( renderTarget === null ) {
  20688. attachmentState = 'default';
  20689. } else {
  20690. const format = renderTarget.texture.format;
  20691. const count = renderTarget.textures.length;
  20692. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  20693. }
  20694. const chainMap = this._getChainMap( attachmentState );
  20695. let renderState = chainMap.get( _chainKeys$3 );
  20696. if ( renderState === undefined ) {
  20697. renderState = new RenderContext();
  20698. chainMap.set( _chainKeys$3, renderState );
  20699. }
  20700. _chainKeys$3.length = 0;
  20701. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  20702. return renderState;
  20703. }
  20704. /**
  20705. * Returns a render context intended for clear operations.
  20706. *
  20707. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  20708. * @return {RenderContext} The render context.
  20709. */
  20710. getForClear( renderTarget = null ) {
  20711. return this.get( _defaultScene, _defaultCamera, renderTarget );
  20712. }
  20713. /**
  20714. * Returns a chain map for the given attachment state.
  20715. *
  20716. * @private
  20717. * @param {string} attachmentState - The attachment state.
  20718. * @return {ChainMap} The chain map.
  20719. */
  20720. _getChainMap( attachmentState ) {
  20721. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  20722. }
  20723. /**
  20724. * Frees internal resources.
  20725. */
  20726. dispose() {
  20727. this.chainMaps = {};
  20728. }
  20729. }
  20730. const _size$3 = /*@__PURE__*/ new Vector3();
  20731. /**
  20732. * This module manages the textures of the renderer.
  20733. *
  20734. * @private
  20735. * @augments DataMap
  20736. */
  20737. class Textures extends DataMap {
  20738. /**
  20739. * Constructs a new texture management component.
  20740. *
  20741. * @param {Renderer} renderer - The renderer.
  20742. * @param {Backend} backend - The renderer's backend.
  20743. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20744. */
  20745. constructor( renderer, backend, info ) {
  20746. super();
  20747. /**
  20748. * The renderer.
  20749. *
  20750. * @type {Renderer}
  20751. */
  20752. this.renderer = renderer;
  20753. /**
  20754. * The backend.
  20755. *
  20756. * @type {Backend}
  20757. */
  20758. this.backend = backend;
  20759. /**
  20760. * Renderer component for managing metrics and monitoring data.
  20761. *
  20762. * @type {Info}
  20763. */
  20764. this.info = info;
  20765. }
  20766. /**
  20767. * Updates the given render target. Based on the given render target configuration,
  20768. * it updates the texture states representing the attachments of the framebuffer.
  20769. *
  20770. * @param {RenderTarget} renderTarget - The render target to update.
  20771. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  20772. */
  20773. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  20774. const renderTargetData = this.get( renderTarget );
  20775. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  20776. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  20777. const textures = renderTarget.textures;
  20778. const size = this.getSize( textures[ 0 ] );
  20779. const mipWidth = size.width >> activeMipmapLevel;
  20780. const mipHeight = size.height >> activeMipmapLevel;
  20781. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  20782. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  20783. let textureNeedsUpdate = false;
  20784. if ( depthTexture === undefined && useDepthTexture ) {
  20785. if ( renderTarget.multiview === true && size.depth > 1 ) {
  20786. depthTexture = new DepthArrayTexture();
  20787. } else {
  20788. depthTexture = new DepthTexture();
  20789. }
  20790. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  20791. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  20792. depthTexture.image.width = mipWidth;
  20793. depthTexture.image.height = mipHeight;
  20794. depthTexture.image.depth = size.depth;
  20795. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  20796. }
  20797. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  20798. textureNeedsUpdate = true;
  20799. if ( depthTexture ) {
  20800. depthTexture.needsUpdate = true;
  20801. depthTexture.image.width = mipWidth;
  20802. depthTexture.image.height = mipHeight;
  20803. depthTexture.image.depth = depthTexture.isDepthArrayTexture ? depthTexture.image.depth : 1;
  20804. }
  20805. }
  20806. renderTargetData.width = size.width;
  20807. renderTargetData.height = size.height;
  20808. renderTargetData.textures = textures;
  20809. renderTargetData.depthTexture = depthTexture || null;
  20810. renderTargetData.depth = renderTarget.depthBuffer;
  20811. renderTargetData.stencil = renderTarget.stencilBuffer;
  20812. renderTargetData.renderTarget = renderTarget;
  20813. if ( renderTargetData.sampleCount !== sampleCount ) {
  20814. textureNeedsUpdate = true;
  20815. if ( depthTexture ) {
  20816. depthTexture.needsUpdate = true;
  20817. }
  20818. renderTargetData.sampleCount = sampleCount;
  20819. }
  20820. //
  20821. const options = { sampleCount };
  20822. // XR render targets require no texture updates
  20823. if ( renderTarget.isXRRenderTarget !== true ) {
  20824. for ( let i = 0; i < textures.length; i ++ ) {
  20825. const texture = textures[ i ];
  20826. texture.isTextureArray = renderTarget.multiview === true && size.depth > 1;
  20827. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  20828. this.updateTexture( texture, options );
  20829. }
  20830. if ( depthTexture ) {
  20831. this.updateTexture( depthTexture, options );
  20832. }
  20833. }
  20834. // dispose handler
  20835. if ( renderTargetData.initialized !== true ) {
  20836. renderTargetData.initialized = true;
  20837. // dispose
  20838. const onDispose = () => {
  20839. renderTarget.removeEventListener( 'dispose', onDispose );
  20840. for ( let i = 0; i < textures.length; i ++ ) {
  20841. this._destroyTexture( textures[ i ] );
  20842. }
  20843. if ( depthTexture ) {
  20844. this._destroyTexture( depthTexture );
  20845. }
  20846. this.delete( renderTarget );
  20847. };
  20848. renderTarget.addEventListener( 'dispose', onDispose );
  20849. }
  20850. }
  20851. /**
  20852. * Updates the given texture. Depending on the texture state, this method
  20853. * triggers the upload of texture data to the GPU memory. If the texture data are
  20854. * not yet ready for the upload, it uses default texture data for as a placeholder.
  20855. *
  20856. * @param {Texture} texture - The texture to update.
  20857. * @param {Object} [options={}] - The options.
  20858. */
  20859. updateTexture( texture, options = {} ) {
  20860. const textureData = this.get( texture );
  20861. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  20862. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  20863. const backend = this.backend;
  20864. if ( isRenderTarget && textureData.initialized === true ) {
  20865. // it's an update
  20866. backend.destroySampler( texture );
  20867. backend.destroyTexture( texture );
  20868. }
  20869. //
  20870. if ( texture.isFramebufferTexture ) {
  20871. const renderTarget = this.renderer.getRenderTarget();
  20872. if ( renderTarget ) {
  20873. texture.type = renderTarget.texture.type;
  20874. } else {
  20875. texture.type = UnsignedByteType;
  20876. }
  20877. }
  20878. //
  20879. const { width, height, depth } = this.getSize( texture );
  20880. options.width = width;
  20881. options.height = height;
  20882. options.depth = depth;
  20883. options.needsMipmaps = this.needsMipmaps( texture );
  20884. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  20885. //
  20886. if ( isRenderTarget || texture.isStorageTexture === true ) {
  20887. backend.createSampler( texture );
  20888. backend.createTexture( texture, options );
  20889. textureData.generation = texture.version;
  20890. } else {
  20891. const needsCreate = textureData.initialized !== true;
  20892. if ( needsCreate ) backend.createSampler( texture );
  20893. if ( texture.version > 0 ) {
  20894. const image = texture.image;
  20895. if ( image === undefined ) {
  20896. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  20897. } else if ( image.complete === false ) {
  20898. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  20899. } else {
  20900. if ( texture.images ) {
  20901. const images = [];
  20902. for ( const image of texture.images ) {
  20903. images.push( image );
  20904. }
  20905. options.images = images;
  20906. } else {
  20907. options.image = image;
  20908. }
  20909. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  20910. backend.createTexture( texture, options );
  20911. textureData.isDefaultTexture = false;
  20912. textureData.generation = texture.version;
  20913. }
  20914. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  20915. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  20916. }
  20917. } else {
  20918. // async update
  20919. backend.createDefaultTexture( texture );
  20920. textureData.isDefaultTexture = true;
  20921. textureData.generation = texture.version;
  20922. }
  20923. }
  20924. // dispose handler
  20925. if ( textureData.initialized !== true ) {
  20926. textureData.initialized = true;
  20927. textureData.generation = texture.version;
  20928. //
  20929. this.info.memory.textures ++;
  20930. // dispose
  20931. const onDispose = () => {
  20932. texture.removeEventListener( 'dispose', onDispose );
  20933. this._destroyTexture( texture );
  20934. };
  20935. texture.addEventListener( 'dispose', onDispose );
  20936. }
  20937. //
  20938. textureData.version = texture.version;
  20939. }
  20940. /**
  20941. * Computes the size of the given texture and writes the result
  20942. * into the target vector. This vector is also returned by the
  20943. * method.
  20944. *
  20945. * If no texture data are available for the compute yet, the method
  20946. * returns default size values.
  20947. *
  20948. * @param {Texture} texture - The texture to compute the size for.
  20949. * @param {Vector3} target - The target vector.
  20950. * @return {Vector3} The target vector.
  20951. */
  20952. getSize( texture, target = _size$3 ) {
  20953. let image = texture.images ? texture.images[ 0 ] : texture.image;
  20954. if ( image ) {
  20955. if ( image.image !== undefined ) image = image.image;
  20956. target.width = image.width || 1;
  20957. target.height = image.height || 1;
  20958. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  20959. } else {
  20960. target.width = target.height = target.depth = 1;
  20961. }
  20962. return target;
  20963. }
  20964. /**
  20965. * Computes the number of mipmap levels for the given texture.
  20966. *
  20967. * @param {Texture} texture - The texture.
  20968. * @param {number} width - The texture's width.
  20969. * @param {number} height - The texture's height.
  20970. * @return {number} The number of mipmap levels.
  20971. */
  20972. getMipLevels( texture, width, height ) {
  20973. let mipLevelCount;
  20974. if ( texture.isCompressedTexture ) {
  20975. if ( texture.mipmaps ) {
  20976. mipLevelCount = texture.mipmaps.length;
  20977. } else {
  20978. mipLevelCount = 1;
  20979. }
  20980. } else {
  20981. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  20982. }
  20983. return mipLevelCount;
  20984. }
  20985. /**
  20986. * Returns `true` if the given texture requires mipmaps.
  20987. *
  20988. * @param {Texture} texture - The texture.
  20989. * @return {boolean} Whether mipmaps are required or not.
  20990. */
  20991. needsMipmaps( texture ) {
  20992. return texture.isCompressedTexture === true || texture.generateMipmaps;
  20993. }
  20994. /**
  20995. * Frees internal resource when the given texture isn't
  20996. * required anymore.
  20997. *
  20998. * @param {Texture} texture - The texture to destroy.
  20999. */
  21000. _destroyTexture( texture ) {
  21001. if ( this.has( texture ) === true ) {
  21002. this.backend.destroySampler( texture );
  21003. this.backend.destroyTexture( texture );
  21004. this.delete( texture );
  21005. this.info.memory.textures --;
  21006. }
  21007. }
  21008. }
  21009. /**
  21010. * A four-component version of {@link Color} which is internally
  21011. * used by the renderer to represents clear color with alpha as
  21012. * one object.
  21013. *
  21014. * @private
  21015. * @augments Color
  21016. */
  21017. class Color4 extends Color {
  21018. /**
  21019. * Constructs a new four-component color.
  21020. * You can also pass a single THREE.Color, hex or
  21021. * string argument to this constructor.
  21022. *
  21023. * @param {number|string} [r=1] - The red value.
  21024. * @param {number} [g=1] - The green value.
  21025. * @param {number} [b=1] - The blue value.
  21026. * @param {number} [a=1] - The alpha value.
  21027. */
  21028. constructor( r, g, b, a = 1 ) {
  21029. super( r, g, b );
  21030. this.a = a;
  21031. }
  21032. /**
  21033. * Overwrites the default to honor alpha.
  21034. * You can also pass a single THREE.Color, hex or
  21035. * string argument to this method.
  21036. *
  21037. * @param {number|string|Color} r - The red value.
  21038. * @param {number} g - The green value.
  21039. * @param {number} b - The blue value.
  21040. * @param {number} [a=1] - The alpha value.
  21041. * @return {Color4} A reference to this object.
  21042. */
  21043. set( r, g, b, a = 1 ) {
  21044. this.a = a;
  21045. return super.set( r, g, b );
  21046. }
  21047. /**
  21048. * Overwrites the default to honor alpha.
  21049. *
  21050. * @param {Color4} color - The color to copy.
  21051. * @return {Color4} A reference to this object.
  21052. */
  21053. copy( color ) {
  21054. if ( color.a !== undefined ) this.a = color.a;
  21055. return super.copy( color );
  21056. }
  21057. /**
  21058. * Overwrites the default to honor alpha.
  21059. *
  21060. * @return {Color4} The cloned color.
  21061. */
  21062. clone() {
  21063. return new this.constructor( this.r, this.g, this.b, this.a );
  21064. }
  21065. }
  21066. /**
  21067. * Special version of {@link PropertyNode} which is used for parameters.
  21068. *
  21069. * @augments PropertyNode
  21070. */
  21071. class ParameterNode extends PropertyNode {
  21072. static get type() {
  21073. return 'ParameterNode';
  21074. }
  21075. /**
  21076. * Constructs a new parameter node.
  21077. *
  21078. * @param {string} nodeType - The type of the node.
  21079. * @param {?string} [name=null] - The name of the parameter in the shader.
  21080. */
  21081. constructor( nodeType, name = null ) {
  21082. super( nodeType, name );
  21083. /**
  21084. * This flag can be used for type testing.
  21085. *
  21086. * @type {boolean}
  21087. * @readonly
  21088. * @default true
  21089. */
  21090. this.isParameterNode = true;
  21091. }
  21092. getHash() {
  21093. return this.uuid;
  21094. }
  21095. generate() {
  21096. return this.name;
  21097. }
  21098. }
  21099. /**
  21100. * TSL function for creating a parameter node.
  21101. *
  21102. * @tsl
  21103. * @function
  21104. * @param {string} type - The type of the node.
  21105. * @param {?string} name - The name of the parameter in the shader.
  21106. * @returns {ParameterNode}
  21107. */
  21108. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  21109. /**
  21110. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  21111. * They are usually needed in cases like `If`, `Else`.
  21112. *
  21113. * @augments Node
  21114. */
  21115. class StackNode extends Node {
  21116. static get type() {
  21117. return 'StackNode';
  21118. }
  21119. /**
  21120. * Constructs a new stack node.
  21121. *
  21122. * @param {?StackNode} [parent=null] - The parent stack node.
  21123. */
  21124. constructor( parent = null ) {
  21125. super();
  21126. /**
  21127. * List of nodes.
  21128. *
  21129. * @type {Array<Node>}
  21130. */
  21131. this.nodes = [];
  21132. /**
  21133. * The output node.
  21134. *
  21135. * @type {?Node}
  21136. * @default null
  21137. */
  21138. this.outputNode = null;
  21139. /**
  21140. * The parent stack node.
  21141. *
  21142. * @type {?StackNode}
  21143. * @default null
  21144. */
  21145. this.parent = parent;
  21146. /**
  21147. * The current conditional node.
  21148. *
  21149. * @private
  21150. * @type {ConditionalNode}
  21151. * @default null
  21152. */
  21153. this._currentCond = null;
  21154. /**
  21155. * The expression node. Only
  21156. * relevant for Switch/Case.
  21157. *
  21158. * @private
  21159. * @type {Node}
  21160. * @default null
  21161. */
  21162. this._expressionNode = null;
  21163. /**
  21164. * This flag can be used for type testing.
  21165. *
  21166. * @type {boolean}
  21167. * @readonly
  21168. * @default true
  21169. */
  21170. this.isStackNode = true;
  21171. }
  21172. getNodeType( builder ) {
  21173. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  21174. }
  21175. getMemberType( builder, name ) {
  21176. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  21177. }
  21178. /**
  21179. * Adds a node to this stack.
  21180. *
  21181. * @param {Node} node - The node to add.
  21182. * @return {StackNode} A reference to this stack node.
  21183. */
  21184. add( node ) {
  21185. this.nodes.push( node );
  21186. return this;
  21187. }
  21188. /**
  21189. * Represent an `if` statement in TSL.
  21190. *
  21191. * @param {Node} boolNode - Represents the condition.
  21192. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21193. * @return {StackNode} A reference to this stack node.
  21194. */
  21195. If( boolNode, method ) {
  21196. const methodNode = new ShaderNode( method );
  21197. this._currentCond = select( boolNode, methodNode );
  21198. return this.add( this._currentCond );
  21199. }
  21200. /**
  21201. * Represent an `elseif` statement in TSL.
  21202. *
  21203. * @param {Node} boolNode - Represents the condition.
  21204. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21205. * @return {StackNode} A reference to this stack node.
  21206. */
  21207. ElseIf( boolNode, method ) {
  21208. const methodNode = new ShaderNode( method );
  21209. const ifNode = select( boolNode, methodNode );
  21210. this._currentCond.elseNode = ifNode;
  21211. this._currentCond = ifNode;
  21212. return this;
  21213. }
  21214. /**
  21215. * Represent an `else` statement in TSL.
  21216. *
  21217. * @param {Function} method - TSL code which is executed in the `else` case.
  21218. * @return {StackNode} A reference to this stack node.
  21219. */
  21220. Else( method ) {
  21221. this._currentCond.elseNode = new ShaderNode( method );
  21222. return this;
  21223. }
  21224. /**
  21225. * Represents a `switch` statement in TSL.
  21226. *
  21227. * @param {any} expression - Represents the expression.
  21228. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21229. * @return {StackNode} A reference to this stack node.
  21230. */
  21231. Switch( expression ) {
  21232. this._expressionNode = nodeObject( expression );
  21233. return this;
  21234. }
  21235. /**
  21236. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  21237. * The last parameter must be the callback method that should be executed in the `true` case.
  21238. *
  21239. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  21240. * @return {StackNode} A reference to this stack node.
  21241. */
  21242. Case( ...params ) {
  21243. const caseNodes = [];
  21244. // extract case nodes from the parameter list
  21245. if ( params.length >= 2 ) {
  21246. for ( let i = 0; i < params.length - 1; i ++ ) {
  21247. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  21248. }
  21249. } else {
  21250. throw new Error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  21251. }
  21252. // extract method
  21253. const method = params[ params.length - 1 ];
  21254. const methodNode = new ShaderNode( method );
  21255. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  21256. let caseNode = caseNodes[ 0 ];
  21257. for ( let i = 1; i < caseNodes.length; i ++ ) {
  21258. caseNode = caseNode.or( caseNodes[ i ] );
  21259. }
  21260. // build condition
  21261. const condNode = select( caseNode, methodNode );
  21262. if ( this._currentCond === null ) {
  21263. this._currentCond = condNode;
  21264. return this.add( this._currentCond );
  21265. } else {
  21266. this._currentCond.elseNode = condNode;
  21267. this._currentCond = condNode;
  21268. return this;
  21269. }
  21270. }
  21271. /**
  21272. * Represents the default code block of a Switch/Case statement.
  21273. *
  21274. * @param {Function} method - TSL code which is executed in the `else` case.
  21275. * @return {StackNode} A reference to this stack node.
  21276. */
  21277. Default( method ) {
  21278. this.Else( method );
  21279. return this;
  21280. }
  21281. build( builder, ...params ) {
  21282. const previousStack = getCurrentStack();
  21283. setCurrentStack( this );
  21284. for ( const node of this.nodes ) {
  21285. node.build( builder, 'void' );
  21286. }
  21287. setCurrentStack( previousStack );
  21288. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  21289. }
  21290. // Deprecated
  21291. /**
  21292. * @function
  21293. * @deprecated since r168. Use {@link StackNode#Else} instead.
  21294. *
  21295. * @param {...any} params
  21296. * @returns {StackNode}
  21297. */
  21298. else( ...params ) { // @deprecated, r168
  21299. console.warn( 'THREE.TSL: .else() has been renamed to .Else().' );
  21300. return this.Else( ...params );
  21301. }
  21302. /**
  21303. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  21304. *
  21305. * @param {...any} params
  21306. * @returns {StackNode}
  21307. */
  21308. elseif( ...params ) { // @deprecated, r168
  21309. console.warn( 'THREE.TSL: .elseif() has been renamed to .ElseIf().' );
  21310. return this.ElseIf( ...params );
  21311. }
  21312. }
  21313. /**
  21314. * TSL function for creating a stack node.
  21315. *
  21316. * @tsl
  21317. * @function
  21318. * @param {?StackNode} [parent=null] - The parent stack node.
  21319. * @returns {StackNode}
  21320. */
  21321. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  21322. /**
  21323. * Generates a layout for struct members.
  21324. * This function takes an object representing struct members and returns an array of member layouts.
  21325. * Each member layout includes the member's name, type, and whether it is atomic.
  21326. *
  21327. * @param {Object.<string, string|Object>} members - An object where keys are member names and values are either types (as strings) or objects with type and atomic properties.
  21328. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  21329. */
  21330. function getMembersLayout( members ) {
  21331. return Object.entries( members ).map( ( [ name, value ] ) => {
  21332. if ( typeof value === 'string' ) {
  21333. return { name, type: value, atomic: false };
  21334. }
  21335. return { name, type: value.type, atomic: value.atomic || false };
  21336. } );
  21337. }
  21338. /**
  21339. * Represents a struct type node in the node-based system.
  21340. * This class is used to define and manage the layout and types of struct members.
  21341. * It extends the base Node class and provides methods to get the length of the struct,
  21342. * retrieve member types, and generate the struct type for a builder.
  21343. *
  21344. * @augments Node
  21345. */
  21346. class StructTypeNode extends Node {
  21347. static get type() {
  21348. return 'StructTypeNode';
  21349. }
  21350. /**
  21351. * Creates an instance of StructTypeNode.
  21352. *
  21353. * @param {Object} membersLayout - The layout of the members for the struct.
  21354. * @param {?string} [name=null] - The optional name of the struct.
  21355. */
  21356. constructor( membersLayout, name = null ) {
  21357. super( 'struct' );
  21358. /**
  21359. * The layout of the members for the struct
  21360. *
  21361. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  21362. */
  21363. this.membersLayout = getMembersLayout( membersLayout );
  21364. /**
  21365. * The name of the struct.
  21366. *
  21367. * @type {?string}
  21368. * @default null
  21369. */
  21370. this.name = name;
  21371. /**
  21372. * This flag can be used for type testing.
  21373. *
  21374. * @type {boolean}
  21375. * @readonly
  21376. * @default true
  21377. */
  21378. this.isStructLayoutNode = true;
  21379. }
  21380. /**
  21381. * Returns the length of the struct.
  21382. * The length is calculated by summing the lengths of the struct's members.
  21383. *
  21384. * @returns {number} The length of the struct.
  21385. */
  21386. getLength() {
  21387. let length = 0;
  21388. for ( const member of this.membersLayout ) {
  21389. length += getLengthFromType( member.type );
  21390. }
  21391. return length;
  21392. }
  21393. getMemberType( builder, name ) {
  21394. const member = this.membersLayout.find( m => m.name === name );
  21395. return member ? member.type : 'void';
  21396. }
  21397. getNodeType( builder ) {
  21398. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  21399. return structType.name;
  21400. }
  21401. setup( builder ) {
  21402. builder.addInclude( this );
  21403. }
  21404. generate( builder ) {
  21405. return this.getNodeType( builder );
  21406. }
  21407. }
  21408. /**
  21409. * StructNode allows to create custom structures with multiple members.
  21410. * This can also be used to define structures in attribute and uniform data.
  21411. *
  21412. * ```js
  21413. * // Define a custom struct
  21414. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  21415. *
  21416. * // Create a new instance of the struct
  21417. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  21418. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  21419. *
  21420. * // Access the struct members
  21421. * const min = bb.get( 'min' );
  21422. *
  21423. * // Assign a new value to a member
  21424. * min.assign( vec3() );
  21425. * ```
  21426. * @augments Node
  21427. */
  21428. class StructNode extends Node {
  21429. static get type() {
  21430. return 'StructNode';
  21431. }
  21432. constructor( structLayoutNode, values ) {
  21433. super( 'vec3' );
  21434. this.structLayoutNode = structLayoutNode;
  21435. this.values = values;
  21436. this.isStructNode = true;
  21437. }
  21438. getNodeType( builder ) {
  21439. return this.structLayoutNode.getNodeType( builder );
  21440. }
  21441. getMemberType( builder, name ) {
  21442. return this.structLayoutNode.getMemberType( builder, name );
  21443. }
  21444. generate( builder ) {
  21445. const nodeVar = builder.getVarFromNode( this );
  21446. const structType = nodeVar.type;
  21447. const propertyName = builder.getPropertyName( nodeVar );
  21448. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  21449. return nodeVar.name;
  21450. }
  21451. }
  21452. /**
  21453. * TSL function for creating a struct node.
  21454. *
  21455. * @tsl
  21456. * @function
  21457. * @param {Object} membersLayout - The layout of the struct members.
  21458. * @param {?string} [name=null] - The name of the struct.
  21459. * @returns {Function} The struct function.
  21460. */
  21461. const struct = ( membersLayout, name = null ) => {
  21462. const structLayout = new StructTypeNode( membersLayout, name );
  21463. const struct = ( ...params ) => {
  21464. let values = null;
  21465. if ( params.length > 0 ) {
  21466. if ( params[ 0 ].isNode ) {
  21467. values = {};
  21468. const names = Object.keys( membersLayout );
  21469. for ( let i = 0; i < params.length; i ++ ) {
  21470. values[ names[ i ] ] = params[ i ];
  21471. }
  21472. } else {
  21473. values = params[ 0 ];
  21474. }
  21475. }
  21476. return nodeObject( new StructNode( structLayout, values ) );
  21477. };
  21478. struct.layout = structLayout;
  21479. struct.isStruct = true;
  21480. return struct;
  21481. };
  21482. /**
  21483. * This node can be used to define multiple outputs in a shader programs.
  21484. *
  21485. * @augments Node
  21486. */
  21487. class OutputStructNode extends Node {
  21488. static get type() {
  21489. return 'OutputStructNode';
  21490. }
  21491. /**
  21492. * Constructs a new output struct node. The constructor can be invoked with an
  21493. * arbitrary number of nodes representing the members.
  21494. *
  21495. * @param {...Node} members - A parameter list of nodes.
  21496. */
  21497. constructor( ...members ) {
  21498. super();
  21499. /**
  21500. * An array of nodes which defines the output.
  21501. *
  21502. * @type {Array<Node>}
  21503. */
  21504. this.members = members;
  21505. /**
  21506. * This flag can be used for type testing.
  21507. *
  21508. * @type {boolean}
  21509. * @readonly
  21510. * @default true
  21511. */
  21512. this.isOutputStructNode = true;
  21513. }
  21514. getNodeType( builder ) {
  21515. const properties = builder.getNodeProperties( this );
  21516. if ( properties.membersLayout === undefined ) {
  21517. const members = this.members;
  21518. const membersLayout = [];
  21519. for ( let i = 0; i < members.length; i ++ ) {
  21520. const name = 'm' + i;
  21521. const type = members[ i ].getNodeType( builder );
  21522. membersLayout.push( { name, type, index: i } );
  21523. }
  21524. properties.membersLayout = membersLayout;
  21525. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  21526. }
  21527. return properties.structType.name;
  21528. }
  21529. generate( builder ) {
  21530. const propertyName = builder.getOutputStructName();
  21531. const members = this.members;
  21532. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  21533. for ( let i = 0; i < members.length; i ++ ) {
  21534. const snippet = members[ i ].build( builder );
  21535. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  21536. }
  21537. return propertyName;
  21538. }
  21539. }
  21540. /**
  21541. * TSL function for creating an output struct node.
  21542. *
  21543. * @tsl
  21544. * @function
  21545. * @param {...Node} members - A parameter list of nodes.
  21546. * @returns {OutputStructNode}
  21547. */
  21548. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  21549. /**
  21550. * Returns the MRT texture index for the given name.
  21551. *
  21552. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  21553. * @param {string} name - The name of the MRT texture which index is requested.
  21554. * @return {number} The texture index.
  21555. */
  21556. function getTextureIndex( textures, name ) {
  21557. for ( let i = 0; i < textures.length; i ++ ) {
  21558. if ( textures[ i ].name === name ) {
  21559. return i;
  21560. }
  21561. }
  21562. return -1;
  21563. }
  21564. /**
  21565. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  21566. * post-processing is shown below:
  21567. * ```js
  21568. * const mrtNode = mrt( {
  21569. * output: output,
  21570. * normal: normalView
  21571. * } ) );
  21572. * ```
  21573. * The MRT output is defined as a dictionary.
  21574. *
  21575. * @augments OutputStructNode
  21576. */
  21577. class MRTNode extends OutputStructNode {
  21578. static get type() {
  21579. return 'MRTNode';
  21580. }
  21581. /**
  21582. * Constructs a new output struct node.
  21583. *
  21584. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  21585. */
  21586. constructor( outputNodes ) {
  21587. super();
  21588. /**
  21589. * A dictionary representing the MRT outputs. The key
  21590. * is the name of the output, the value the node which produces
  21591. * the output result.
  21592. *
  21593. * @type {Object<string, Node>}
  21594. */
  21595. this.outputNodes = outputNodes;
  21596. /**
  21597. * This flag can be used for type testing.
  21598. *
  21599. * @type {boolean}
  21600. * @readonly
  21601. * @default true
  21602. */
  21603. this.isMRTNode = true;
  21604. }
  21605. /**
  21606. * Returns `true` if the MRT node has an output with the given name.
  21607. *
  21608. * @param {string} name - The name of the output.
  21609. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  21610. */
  21611. has( name ) {
  21612. return this.outputNodes[ name ] !== undefined;
  21613. }
  21614. /**
  21615. * Returns the output node for the given name.
  21616. *
  21617. * @param {string} name - The name of the output.
  21618. * @return {Node} The output node.
  21619. */
  21620. get( name ) {
  21621. return this.outputNodes[ name ];
  21622. }
  21623. /**
  21624. * Merges the outputs of the given MRT node with the outputs of this node.
  21625. *
  21626. * @param {MRTNode} mrtNode - The MRT to merge.
  21627. * @return {MRTNode} A new MRT node with merged outputs..
  21628. */
  21629. merge( mrtNode ) {
  21630. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  21631. return mrt( outputs );
  21632. }
  21633. setup( builder ) {
  21634. const outputNodes = this.outputNodes;
  21635. const mrt = builder.renderer.getRenderTarget();
  21636. const members = [];
  21637. const textures = mrt.textures;
  21638. for ( const name in outputNodes ) {
  21639. const index = getTextureIndex( textures, name );
  21640. members[ index ] = vec4( outputNodes[ name ] );
  21641. }
  21642. this.members = members;
  21643. return super.setup( builder );
  21644. }
  21645. }
  21646. /**
  21647. * TSL function for creating a MRT node.
  21648. *
  21649. * @tsl
  21650. * @function
  21651. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  21652. * @returns {MRTNode}
  21653. */
  21654. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  21655. /**
  21656. * Generates a hash value in the range `[0, 1]` from the given seed.
  21657. *
  21658. * @tsl
  21659. * @function
  21660. * @param {Node<float>} seed - The seed.
  21661. * @return {Node<float>} The hash value.
  21662. */
  21663. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  21664. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  21665. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  21666. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  21667. const result = word.shiftRight( 22 ).bitXor( word );
  21668. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  21669. } );
  21670. /**
  21671. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21672. * The corners are mapped to `0` and the center to `1`.
  21673. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21674. *
  21675. * @tsl
  21676. * @function
  21677. * @param {Node<float>} x - The value to remap.
  21678. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  21679. * @return {Node<float>} The remapped value.
  21680. */
  21681. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  21682. /**
  21683. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21684. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  21685. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21686. *
  21687. * @tsl
  21688. * @function
  21689. * @param {Node<float>} x - The value to remap.
  21690. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  21691. * @return {Node<float>} The remapped value.
  21692. */
  21693. 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 ) );
  21694. /**
  21695. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  21696. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  21697. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21698. *
  21699. * @tsl
  21700. * @function
  21701. * @param {Node<float>} x - The value to remap.
  21702. * @param {Node<float>} a - First control parameter.
  21703. * @param {Node<float>} b - Second control parameter.
  21704. * @return {Node<float>} The remapped value.
  21705. */
  21706. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  21707. /**
  21708. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  21709. * Reference: {@link https://iquilezles.org/articles/functions/}.
  21710. *
  21711. * @tsl
  21712. * @function
  21713. * @param {Node<float>} x - The value to compute the sin for.
  21714. * @param {Node<float>} k - Controls the amount of bounces.
  21715. * @return {Node<float>} The result value.
  21716. */
  21717. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  21718. // https://github.com/cabbibo/glsl-tri-noise-3d
  21719. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  21720. return x.fract().sub( .5 ).abs();
  21721. } ).setLayout( {
  21722. name: 'tri',
  21723. type: 'float',
  21724. inputs: [
  21725. { name: 'x', type: 'float' }
  21726. ]
  21727. } );
  21728. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  21729. 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. ) ) ) ) );
  21730. } ).setLayout( {
  21731. name: 'tri3',
  21732. type: 'vec3',
  21733. inputs: [
  21734. { name: 'p', type: 'vec3' }
  21735. ]
  21736. } );
  21737. /**
  21738. * Generates a noise value from the given position, speed and time parameters.
  21739. *
  21740. * @tsl
  21741. * @function
  21742. * @param {Node<vec3>} position - The position.
  21743. * @param {Node<float>} speed - The speed.
  21744. * @param {Node<float>} time - The time.
  21745. * @return {Node<float>} The generated noise.
  21746. */
  21747. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  21748. const p = vec3( position ).toVar();
  21749. const z = float( 1.4 ).toVar();
  21750. const rz = float( 0.0 ).toVar();
  21751. const bp = vec3( p ).toVar();
  21752. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  21753. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  21754. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  21755. bp.mulAssign( 1.8 );
  21756. z.mulAssign( 1.5 );
  21757. p.mulAssign( 1.2 );
  21758. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  21759. rz.addAssign( t.div( z ) );
  21760. bp.addAssign( 0.14 );
  21761. } );
  21762. return rz;
  21763. } ).setLayout( {
  21764. name: 'triNoise3D',
  21765. type: 'float',
  21766. inputs: [
  21767. { name: 'position', type: 'vec3' },
  21768. { name: 'speed', type: 'float' },
  21769. { name: 'time', type: 'float' }
  21770. ]
  21771. } );
  21772. /**
  21773. * This class allows to define multiple overloaded versions
  21774. * of the same function. Depending on the parameters of the function
  21775. * call, the node picks the best-fit overloaded version.
  21776. *
  21777. * @augments Node
  21778. */
  21779. class FunctionOverloadingNode extends Node {
  21780. static get type() {
  21781. return 'FunctionOverloadingNode';
  21782. }
  21783. /**
  21784. * Constructs a new function overloading node.
  21785. *
  21786. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  21787. * @param {...Node} parametersNodes - A list of parameter nodes.
  21788. */
  21789. constructor( functionNodes = [], ...parametersNodes ) {
  21790. super();
  21791. /**
  21792. * Array of `Fn` function definitions.
  21793. *
  21794. * @type {Array<Function>}
  21795. */
  21796. this.functionNodes = functionNodes;
  21797. /**
  21798. * A list of parameter nodes.
  21799. *
  21800. * @type {Array<Node>}
  21801. */
  21802. this.parametersNodes = parametersNodes;
  21803. /**
  21804. * The selected overloaded function call.
  21805. *
  21806. * @private
  21807. * @type {ShaderCallNodeInternal}
  21808. */
  21809. this._candidateFnCall = null;
  21810. /**
  21811. * This node is marked as global.
  21812. *
  21813. * @type {boolean}
  21814. * @default true
  21815. */
  21816. this.global = true;
  21817. }
  21818. /**
  21819. * This method is overwritten since the node type is inferred from
  21820. * the function's return type.
  21821. *
  21822. * @param {NodeBuilder} builder - The current node builder.
  21823. * @return {string} The node type.
  21824. */
  21825. getNodeType() {
  21826. return this.functionNodes[ 0 ].shaderNode.layout.type;
  21827. }
  21828. setup( builder ) {
  21829. const params = this.parametersNodes;
  21830. let candidateFnCall = this._candidateFnCall;
  21831. if ( candidateFnCall === null ) {
  21832. let candidateFn = null;
  21833. let candidateScore = -1;
  21834. for ( const functionNode of this.functionNodes ) {
  21835. const shaderNode = functionNode.shaderNode;
  21836. const layout = shaderNode.layout;
  21837. if ( layout === null ) {
  21838. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  21839. }
  21840. const inputs = layout.inputs;
  21841. if ( params.length === inputs.length ) {
  21842. let score = 0;
  21843. for ( let i = 0; i < params.length; i ++ ) {
  21844. const param = params[ i ];
  21845. const input = inputs[ i ];
  21846. if ( param.getNodeType( builder ) === input.type ) {
  21847. score ++;
  21848. } else {
  21849. score = 0;
  21850. }
  21851. }
  21852. if ( score > candidateScore ) {
  21853. candidateFn = functionNode;
  21854. candidateScore = score;
  21855. }
  21856. }
  21857. }
  21858. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  21859. }
  21860. return candidateFnCall;
  21861. }
  21862. }
  21863. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  21864. /**
  21865. * TSL function for creating a function overloading node.
  21866. *
  21867. * @tsl
  21868. * @function
  21869. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  21870. * @returns {FunctionOverloadingNode}
  21871. */
  21872. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  21873. /**
  21874. * Represents the elapsed time in seconds.
  21875. *
  21876. * @tsl
  21877. * @type {UniformNode<float>}
  21878. */
  21879. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  21880. /**
  21881. * Represents the delta time in seconds.
  21882. *
  21883. * @tsl
  21884. * @type {UniformNode<float>}
  21885. */
  21886. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  21887. /**
  21888. * Represents the current frame ID.
  21889. *
  21890. * @tsl
  21891. * @type {UniformNode<uint>}
  21892. */
  21893. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  21894. // Deprecated
  21895. /**
  21896. * @tsl
  21897. * @function
  21898. * @deprecated since r170. Use {@link time} instead.
  21899. *
  21900. * @param {number} [timeScale=1] - The time scale.
  21901. * @returns {UniformNode<float>}
  21902. */
  21903. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  21904. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  21905. return time.mul( timeScale );
  21906. };
  21907. /**
  21908. * @tsl
  21909. * @function
  21910. * @deprecated since r170. Use {@link time} instead.
  21911. *
  21912. * @param {number} [timeScale=1] - The time scale.
  21913. * @returns {UniformNode<float>}
  21914. */
  21915. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  21916. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  21917. return time.mul( timeScale );
  21918. };
  21919. /**
  21920. * @tsl
  21921. * @function
  21922. * @deprecated since r170. Use {@link deltaTime} instead.
  21923. *
  21924. * @param {number} [timeScale=1] - The time scale.
  21925. * @returns {UniformNode<float>}
  21926. */
  21927. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  21928. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  21929. return deltaTime.mul( timeScale );
  21930. };
  21931. /**
  21932. * Generates a sine wave oscillation based on a timer.
  21933. *
  21934. * @tsl
  21935. * @function
  21936. * @param {Node<float>} t - The timer to generate the oscillation with.
  21937. * @return {Node<float>} The oscillation node.
  21938. */
  21939. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  21940. /**
  21941. * Generates a square wave oscillation based on a timer.
  21942. *
  21943. * @tsl
  21944. * @function
  21945. * @param {Node<float>} t - The timer to generate the oscillation with.
  21946. * @return {Node<float>} The oscillation node.
  21947. */
  21948. const oscSquare = ( t = time ) => t.fract().round();
  21949. /**
  21950. * Generates a triangle wave oscillation based on a timer.
  21951. *
  21952. * @tsl
  21953. * @function
  21954. * @param {Node<float>} t - The timer to generate the oscillation with.
  21955. * @return {Node<float>} The oscillation node.
  21956. */
  21957. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  21958. /**
  21959. * Generates a sawtooth wave oscillation based on a timer.
  21960. *
  21961. * @tsl
  21962. * @function
  21963. * @param {Node<float>} t - The timer to generate the oscillation with.
  21964. * @return {Node<float>} The oscillation node.
  21965. */
  21966. const oscSawtooth = ( t = time ) => t.fract();
  21967. /**
  21968. * Rotates the given uv coordinates around a center point
  21969. *
  21970. * @tsl
  21971. * @function
  21972. * @param {Node<vec2>} uv - The uv coordinates.
  21973. * @param {Node<float>} rotation - The rotation defined in radians.
  21974. * @param {Node<vec2>} center - The center of rotation
  21975. * @return {Node<vec2>} The rotated uv coordinates.
  21976. */
  21977. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  21978. return rotate( uv.sub( center ), rotation ).add( center );
  21979. } );
  21980. /**
  21981. * Applies a spherical warping effect to the given uv coordinates.
  21982. *
  21983. * @tsl
  21984. * @function
  21985. * @param {Node<vec2>} uv - The uv coordinates.
  21986. * @param {Node<float>} strength - The strength of the effect.
  21987. * @param {Node<vec2>} center - The center point
  21988. * @return {Node<vec2>} The updated uv coordinates.
  21989. */
  21990. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  21991. const delta = uv.sub( center );
  21992. const delta2 = delta.dot( delta );
  21993. const delta4 = delta2.mul( delta2 );
  21994. const deltaOffset = delta4.mul( strength );
  21995. return uv.add( delta.mul( deltaOffset ) );
  21996. } );
  21997. /**
  21998. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  21999. * oriented always towards the camera.
  22000. *
  22001. * ```js
  22002. * material.vertexNode = billboarding();
  22003. * ```
  22004. *
  22005. * @tsl
  22006. * @function
  22007. * @param {Object} config - The configuration object.
  22008. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  22009. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  22010. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  22011. * @return {Node<vec3>} The updated vertex position in clip space.
  22012. */
  22013. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  22014. let worldMatrix;
  22015. if ( position !== null ) {
  22016. worldMatrix = modelWorldMatrix.toVar();
  22017. worldMatrix[ 3 ][ 0 ] = position.x;
  22018. worldMatrix[ 3 ][ 1 ] = position.y;
  22019. worldMatrix[ 3 ][ 2 ] = position.z;
  22020. } else {
  22021. worldMatrix = modelWorldMatrix;
  22022. }
  22023. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  22024. if ( defined( horizontal ) ) {
  22025. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  22026. modelViewMatrix[ 0 ][ 1 ] = 0;
  22027. modelViewMatrix[ 0 ][ 2 ] = 0;
  22028. }
  22029. if ( defined( vertical ) ) {
  22030. modelViewMatrix[ 1 ][ 0 ] = 0;
  22031. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  22032. modelViewMatrix[ 1 ][ 2 ] = 0;
  22033. }
  22034. modelViewMatrix[ 2 ][ 0 ] = 0;
  22035. modelViewMatrix[ 2 ][ 1 ] = 0;
  22036. modelViewMatrix[ 2 ][ 2 ] = 1;
  22037. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22038. } );
  22039. /**
  22040. * A special version of a screen uv function that involves a depth comparison
  22041. * when computing the final uvs. The function mitigates visual errors when
  22042. * using viewport texture nodes for refraction purposes. Without this function
  22043. * objects in front of a refractive surface might appear on the refractive surface
  22044. * which is incorrect.
  22045. *
  22046. * @tsl
  22047. * @function
  22048. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  22049. * @return {Node<vec2>} The update uv coordinates.
  22050. */
  22051. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  22052. const depth = linearDepth();
  22053. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  22054. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  22055. return finalUV;
  22056. } );
  22057. /**
  22058. * Can be used to compute texture coordinates for animated sprite sheets.
  22059. *
  22060. * ```js
  22061. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  22062. *
  22063. * material.colorNode = texture( spriteSheet, uvNode );
  22064. * ```
  22065. *
  22066. * @augments Node
  22067. */
  22068. class SpriteSheetUVNode extends Node {
  22069. static get type() {
  22070. return 'SpriteSheetUVNode';
  22071. }
  22072. /**
  22073. * Constructs a new sprite sheet uv node.
  22074. *
  22075. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22076. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  22077. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22078. */
  22079. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  22080. super( 'vec2' );
  22081. /**
  22082. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22083. *
  22084. * @type {Node<vec2>}
  22085. */
  22086. this.countNode = countNode;
  22087. /**
  22088. * The uv node.
  22089. *
  22090. * @type {Node<vec2>}
  22091. */
  22092. this.uvNode = uvNode;
  22093. /**
  22094. * The node that defines the current frame/sprite.
  22095. *
  22096. * @type {Node<float>}
  22097. */
  22098. this.frameNode = frameNode;
  22099. }
  22100. setup() {
  22101. const { frameNode, uvNode, countNode } = this;
  22102. const { width, height } = countNode;
  22103. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  22104. const column = frameNum.mod( width );
  22105. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  22106. const scale = countNode.reciprocal();
  22107. const uvFrameOffset = vec2( column, row );
  22108. return uvNode.add( uvFrameOffset ).mul( scale );
  22109. }
  22110. }
  22111. /**
  22112. * TSL function for creating a sprite sheet uv node.
  22113. *
  22114. * @tsl
  22115. * @function
  22116. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22117. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  22118. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22119. * @returns {SpriteSheetUVNode}
  22120. */
  22121. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  22122. /**
  22123. * Can be used for triplanar texture mapping.
  22124. *
  22125. * ```js
  22126. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  22127. * ```
  22128. *
  22129. * @augments Node
  22130. */
  22131. class TriplanarTexturesNode extends Node {
  22132. static get type() {
  22133. return 'TriplanarTexturesNode';
  22134. }
  22135. /**
  22136. * Constructs a new triplanar textures node.
  22137. *
  22138. * @param {Node} textureXNode - First texture node.
  22139. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22140. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22141. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22142. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22143. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22144. */
  22145. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  22146. super( 'vec4' );
  22147. /**
  22148. * First texture node.
  22149. *
  22150. * @type {Node}
  22151. */
  22152. this.textureXNode = textureXNode;
  22153. /**
  22154. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22155. *
  22156. * @type {?Node}
  22157. * @default null
  22158. */
  22159. this.textureYNode = textureYNode;
  22160. /**
  22161. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22162. *
  22163. * @type {?Node}
  22164. * @default null
  22165. */
  22166. this.textureZNode = textureZNode;
  22167. /**
  22168. * The scale node.
  22169. *
  22170. * @type {Node<float>}
  22171. * @default float(1)
  22172. */
  22173. this.scaleNode = scaleNode;
  22174. /**
  22175. * Vertex positions in local space.
  22176. *
  22177. * @type {Node<vec3>}
  22178. * @default positionLocal
  22179. */
  22180. this.positionNode = positionNode;
  22181. /**
  22182. * Normals in local space.
  22183. *
  22184. * @type {Node<vec3>}
  22185. * @default normalLocal
  22186. */
  22187. this.normalNode = normalNode;
  22188. }
  22189. setup() {
  22190. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  22191. // Ref: https://github.com/keijiro/StandardTriplanar
  22192. // Blending factor of triplanar mapping
  22193. let bf = normalNode.abs().normalize();
  22194. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  22195. // Triplanar mapping
  22196. const tx = positionNode.yz.mul( scaleNode );
  22197. const ty = positionNode.zx.mul( scaleNode );
  22198. const tz = positionNode.xy.mul( scaleNode );
  22199. // Base color
  22200. const textureX = textureXNode.value;
  22201. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  22202. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  22203. const cx = texture( textureX, tx ).mul( bf.x );
  22204. const cy = texture( textureY, ty ).mul( bf.y );
  22205. const cz = texture( textureZ, tz ).mul( bf.z );
  22206. return add( cx, cy, cz );
  22207. }
  22208. }
  22209. /**
  22210. * TSL function for creating a triplanar textures node.
  22211. *
  22212. * @tsl
  22213. * @function
  22214. * @param {Node} textureXNode - First texture node.
  22215. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22216. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22217. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22218. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22219. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22220. * @returns {TriplanarTexturesNode}
  22221. */
  22222. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setParameterLength( 1, 6 );
  22223. /**
  22224. * TSL function for creating a triplanar textures node.
  22225. *
  22226. * @tsl
  22227. * @function
  22228. * @param {Node} textureXNode - First texture node.
  22229. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22230. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22231. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22232. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22233. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22234. * @returns {TriplanarTexturesNode}
  22235. */
  22236. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  22237. const _reflectorPlane = new Plane();
  22238. const _normal = new Vector3();
  22239. const _reflectorWorldPosition = new Vector3();
  22240. const _cameraWorldPosition = new Vector3();
  22241. const _rotationMatrix = new Matrix4();
  22242. const _lookAtPosition = new Vector3( 0, 0, -1 );
  22243. const clipPlane = new Vector4();
  22244. const _view = new Vector3();
  22245. const _target = new Vector3();
  22246. const _q = new Vector4();
  22247. const _size$2 = new Vector2();
  22248. const _defaultRT = new RenderTarget();
  22249. const _defaultUV = screenUV.flipX();
  22250. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  22251. let _inReflector = false;
  22252. /**
  22253. * This node can be used to implement mirror-like flat reflective surfaces.
  22254. *
  22255. * ```js
  22256. * const groundReflector = reflector();
  22257. * material.colorNode = groundReflector;
  22258. *
  22259. * const plane = new Mesh( geometry, material );
  22260. * plane.add( groundReflector.target );
  22261. * ```
  22262. *
  22263. * @augments TextureNode
  22264. */
  22265. class ReflectorNode extends TextureNode {
  22266. static get type() {
  22267. return 'ReflectorNode';
  22268. }
  22269. /**
  22270. * Constructs a new reflector node.
  22271. *
  22272. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22273. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22274. * @param {number} [parameters.resolution=1] - The resolution scale.
  22275. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22276. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22277. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22278. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22279. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22280. */
  22281. constructor( parameters = {} ) {
  22282. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  22283. /**
  22284. * A reference to the internal reflector base node which holds the actual implementation.
  22285. *
  22286. * @private
  22287. * @type {ReflectorBaseNode}
  22288. * @default ReflectorBaseNode
  22289. */
  22290. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  22291. /**
  22292. * A reference to the internal depth node.
  22293. *
  22294. * @private
  22295. * @type {?Node}
  22296. * @default null
  22297. */
  22298. this._depthNode = null;
  22299. this.setUpdateMatrix( false );
  22300. }
  22301. /**
  22302. * A reference to the internal reflector node.
  22303. *
  22304. * @type {ReflectorBaseNode}
  22305. */
  22306. get reflector() {
  22307. return this._reflectorBaseNode;
  22308. }
  22309. /**
  22310. * A reference to 3D object the reflector is linked to.
  22311. *
  22312. * @type {Object3D}
  22313. */
  22314. get target() {
  22315. return this._reflectorBaseNode.target;
  22316. }
  22317. /**
  22318. * Returns a node representing the mirror's depth. That can be used
  22319. * to implement more advanced reflection effects like distance attenuation.
  22320. *
  22321. * @return {Node} The depth node.
  22322. */
  22323. getDepthNode() {
  22324. if ( this._depthNode === null ) {
  22325. if ( this._reflectorBaseNode.depth !== true ) {
  22326. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  22327. }
  22328. this._depthNode = nodeObject( new ReflectorNode( {
  22329. defaultTexture: _defaultRT.depthTexture,
  22330. reflector: this._reflectorBaseNode
  22331. } ) );
  22332. }
  22333. return this._depthNode;
  22334. }
  22335. setup( builder ) {
  22336. // ignore if used in post-processing
  22337. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  22338. return super.setup( builder );
  22339. }
  22340. clone() {
  22341. const texture = new this.constructor( this.reflectorNode );
  22342. texture._reflectorBaseNode = this._reflectorBaseNode;
  22343. return texture;
  22344. }
  22345. /**
  22346. * Frees internal resources. Should be called when the node is no longer in use.
  22347. */
  22348. dispose() {
  22349. super.dispose();
  22350. this._reflectorBaseNode.dispose();
  22351. }
  22352. }
  22353. /**
  22354. * Holds the actual implementation of the reflector.
  22355. *
  22356. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  22357. * in `ReflectorNode`, see #29619.
  22358. *
  22359. * @private
  22360. * @augments Node
  22361. */
  22362. class ReflectorBaseNode extends Node {
  22363. static get type() {
  22364. return 'ReflectorBaseNode';
  22365. }
  22366. /**
  22367. * Constructs a new reflector base node.
  22368. *
  22369. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  22370. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22371. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22372. * @param {number} [parameters.resolution=1] - The resolution scale.
  22373. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22374. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22375. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22376. */
  22377. constructor( textureNode, parameters = {} ) {
  22378. super();
  22379. const {
  22380. target = new Object3D(),
  22381. resolution = 1,
  22382. generateMipmaps = false,
  22383. bounces = true,
  22384. depth = false
  22385. } = parameters;
  22386. /**
  22387. * Represents the rendered reflections as a texture node.
  22388. *
  22389. * @type {TextureNode}
  22390. */
  22391. this.textureNode = textureNode;
  22392. /**
  22393. * The 3D object the reflector is linked to.
  22394. *
  22395. * @type {Object3D}
  22396. * @default {new Object3D()}
  22397. */
  22398. this.target = target;
  22399. /**
  22400. * The resolution scale.
  22401. *
  22402. * @type {number}
  22403. * @default {1}
  22404. */
  22405. this.resolution = resolution;
  22406. /**
  22407. * Whether mipmaps should be generated or not.
  22408. *
  22409. * @type {boolean}
  22410. * @default {false}
  22411. */
  22412. this.generateMipmaps = generateMipmaps;
  22413. /**
  22414. * Whether reflectors can render other reflector nodes or not.
  22415. *
  22416. * @type {boolean}
  22417. * @default {true}
  22418. */
  22419. this.bounces = bounces;
  22420. /**
  22421. * Whether depth data should be generated or not.
  22422. *
  22423. * @type {boolean}
  22424. * @default {false}
  22425. */
  22426. this.depth = depth;
  22427. /**
  22428. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  22429. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  22430. *
  22431. * @type {string}
  22432. * @default 'render'
  22433. */
  22434. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  22435. /**
  22436. * Weak map for managing virtual cameras.
  22437. *
  22438. * @type {WeakMap<Camera, Camera>}
  22439. */
  22440. this.virtualCameras = new WeakMap();
  22441. /**
  22442. * Weak map for managing render targets.
  22443. *
  22444. * @type {Map<Camera, RenderTarget>}
  22445. */
  22446. this.renderTargets = new Map();
  22447. /**
  22448. * Force render even if reflector is facing away from camera.
  22449. *
  22450. * @type {boolean}
  22451. * @default {false}
  22452. */
  22453. this.forceUpdate = false;
  22454. }
  22455. /**
  22456. * Updates the resolution of the internal render target.
  22457. *
  22458. * @private
  22459. * @param {RenderTarget} renderTarget - The render target to resize.
  22460. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  22461. */
  22462. _updateResolution( renderTarget, renderer ) {
  22463. const resolution = this.resolution;
  22464. renderer.getDrawingBufferSize( _size$2 );
  22465. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  22466. }
  22467. setup( builder ) {
  22468. this._updateResolution( _defaultRT, builder.renderer );
  22469. return super.setup( builder );
  22470. }
  22471. /**
  22472. * Frees internal resources. Should be called when the node is no longer in use.
  22473. */
  22474. dispose() {
  22475. super.dispose();
  22476. for ( const renderTarget of this.renderTargets.values() ) {
  22477. renderTarget.dispose();
  22478. }
  22479. }
  22480. /**
  22481. * Returns a virtual camera for the given camera. The virtual camera is used to
  22482. * render the scene from the reflector's view so correct reflections can be produced.
  22483. *
  22484. * @param {Camera} camera - The scene's camera.
  22485. * @return {Camera} The corresponding virtual camera.
  22486. */
  22487. getVirtualCamera( camera ) {
  22488. let virtualCamera = this.virtualCameras.get( camera );
  22489. if ( virtualCamera === undefined ) {
  22490. virtualCamera = camera.clone();
  22491. this.virtualCameras.set( camera, virtualCamera );
  22492. }
  22493. return virtualCamera;
  22494. }
  22495. /**
  22496. * Returns a render target for the given camera. The reflections are rendered
  22497. * into this render target.
  22498. *
  22499. * @param {Camera} camera - The scene's camera.
  22500. * @return {RenderTarget} The render target.
  22501. */
  22502. getRenderTarget( camera ) {
  22503. let renderTarget = this.renderTargets.get( camera );
  22504. if ( renderTarget === undefined ) {
  22505. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  22506. if ( this.generateMipmaps === true ) {
  22507. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  22508. renderTarget.texture.generateMipmaps = true;
  22509. }
  22510. if ( this.depth === true ) {
  22511. renderTarget.depthTexture = new DepthTexture();
  22512. }
  22513. this.renderTargets.set( camera, renderTarget );
  22514. }
  22515. return renderTarget;
  22516. }
  22517. updateBefore( frame ) {
  22518. if ( this.bounces === false && _inReflector ) return false;
  22519. _inReflector = true;
  22520. const { scene, camera, renderer, material } = frame;
  22521. const { target } = this;
  22522. const virtualCamera = this.getVirtualCamera( camera );
  22523. const renderTarget = this.getRenderTarget( virtualCamera );
  22524. renderer.getDrawingBufferSize( _size$2 );
  22525. this._updateResolution( renderTarget, renderer );
  22526. //
  22527. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  22528. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  22529. _rotationMatrix.extractRotation( target.matrixWorld );
  22530. _normal.set( 0, 0, 1 );
  22531. _normal.applyMatrix4( _rotationMatrix );
  22532. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  22533. // Avoid rendering when reflector is facing away unless forcing an update
  22534. const isFacingAway = _view.dot( _normal ) > 0;
  22535. if ( isFacingAway === true && this.forceUpdate === false ) return;
  22536. _view.reflect( _normal ).negate();
  22537. _view.add( _reflectorWorldPosition );
  22538. _rotationMatrix.extractRotation( camera.matrixWorld );
  22539. _lookAtPosition.set( 0, 0, -1 );
  22540. _lookAtPosition.applyMatrix4( _rotationMatrix );
  22541. _lookAtPosition.add( _cameraWorldPosition );
  22542. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  22543. _target.reflect( _normal ).negate();
  22544. _target.add( _reflectorWorldPosition );
  22545. //
  22546. virtualCamera.coordinateSystem = camera.coordinateSystem;
  22547. virtualCamera.position.copy( _view );
  22548. virtualCamera.up.set( 0, 1, 0 );
  22549. virtualCamera.up.applyMatrix4( _rotationMatrix );
  22550. virtualCamera.up.reflect( _normal );
  22551. virtualCamera.lookAt( _target );
  22552. virtualCamera.near = camera.near;
  22553. virtualCamera.far = camera.far;
  22554. virtualCamera.updateMatrixWorld();
  22555. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  22556. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  22557. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  22558. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  22559. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  22560. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  22561. const projectionMatrix = virtualCamera.projectionMatrix;
  22562. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  22563. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  22564. _q.z = -1;
  22565. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  22566. // Calculate the scaled plane vector
  22567. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  22568. const clipBias = 0;
  22569. // Replacing the third row of the projection matrix
  22570. projectionMatrix.elements[ 2 ] = clipPlane.x;
  22571. projectionMatrix.elements[ 6 ] = clipPlane.y;
  22572. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  22573. projectionMatrix.elements[ 14 ] = clipPlane.w;
  22574. //
  22575. this.textureNode.value = renderTarget.texture;
  22576. if ( this.depth === true ) {
  22577. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  22578. }
  22579. material.visible = false;
  22580. const currentRenderTarget = renderer.getRenderTarget();
  22581. const currentMRT = renderer.getMRT();
  22582. const currentAutoClear = renderer.autoClear;
  22583. renderer.setMRT( null );
  22584. renderer.setRenderTarget( renderTarget );
  22585. renderer.autoClear = true;
  22586. renderer.render( scene, virtualCamera );
  22587. renderer.setMRT( currentMRT );
  22588. renderer.setRenderTarget( currentRenderTarget );
  22589. renderer.autoClear = currentAutoClear;
  22590. material.visible = true;
  22591. _inReflector = false;
  22592. this.forceUpdate = false;
  22593. }
  22594. }
  22595. /**
  22596. * TSL function for creating a reflector node.
  22597. *
  22598. * @tsl
  22599. * @function
  22600. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22601. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22602. * @param {number} [parameters.resolution=1] - The resolution scale.
  22603. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22604. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22605. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22606. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22607. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22608. * @returns {ReflectorNode}
  22609. */
  22610. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  22611. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  22612. /**
  22613. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  22614. *
  22615. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  22616. *
  22617. * @private
  22618. * @augments BufferGeometry
  22619. */
  22620. class QuadGeometry extends BufferGeometry {
  22621. /**
  22622. * Constructs a new quad geometry.
  22623. *
  22624. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  22625. */
  22626. constructor( flipY = false ) {
  22627. super();
  22628. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  22629. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  22630. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  22631. }
  22632. }
  22633. const _geometry = /*@__PURE__*/ new QuadGeometry();
  22634. /**
  22635. * This module is a helper for passes which need to render a full
  22636. * screen effect which is quite common in context of post processing.
  22637. *
  22638. * The intended usage is to reuse a single quad mesh for rendering
  22639. * subsequent passes by just reassigning the `material` reference.
  22640. *
  22641. * Note: This module can only be used with `WebGPURenderer`.
  22642. *
  22643. * @augments Mesh
  22644. */
  22645. class QuadMesh extends Mesh {
  22646. /**
  22647. * Constructs a new quad mesh.
  22648. *
  22649. * @param {?Material} [material=null] - The material to render the quad mesh with.
  22650. */
  22651. constructor( material = null ) {
  22652. super( _geometry, material );
  22653. /**
  22654. * The camera to render the quad mesh with.
  22655. *
  22656. * @type {OrthographicCamera}
  22657. * @readonly
  22658. */
  22659. this.camera = _camera;
  22660. /**
  22661. * This flag can be used for type testing.
  22662. *
  22663. * @type {boolean}
  22664. * @readonly
  22665. * @default true
  22666. */
  22667. this.isQuadMesh = true;
  22668. }
  22669. /**
  22670. * Async version of `render()`.
  22671. *
  22672. * @async
  22673. * @param {Renderer} renderer - The renderer.
  22674. * @return {Promise} A Promise that resolves when the render has been finished.
  22675. */
  22676. async renderAsync( renderer ) {
  22677. return renderer.renderAsync( this, _camera );
  22678. }
  22679. /**
  22680. * Renders the quad mesh
  22681. *
  22682. * @param {Renderer} renderer - The renderer.
  22683. */
  22684. render( renderer ) {
  22685. renderer.render( this, _camera );
  22686. }
  22687. }
  22688. const _size$1 = /*@__PURE__*/ new Vector2();
  22689. /**
  22690. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  22691. * This module is especially relevant in context of post processing where certain nodes require
  22692. * texture input for their effects. With the helper function `convertToTexture()` which is based
  22693. * on this module, the node system can automatically ensure texture input if required.
  22694. *
  22695. * @augments TextureNode
  22696. */
  22697. class RTTNode extends TextureNode {
  22698. static get type() {
  22699. return 'RTTNode';
  22700. }
  22701. /**
  22702. * Constructs a new RTT node.
  22703. *
  22704. * @param {Node} node - The node to render a texture with.
  22705. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  22706. * @param {?number} [height=null] - The height of the internal render target.
  22707. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  22708. */
  22709. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  22710. const renderTarget = new RenderTarget( width, height, options );
  22711. super( renderTarget.texture, uv() );
  22712. /**
  22713. * The node to render a texture with.
  22714. *
  22715. * @type {Node}
  22716. */
  22717. this.node = node;
  22718. /**
  22719. * The width of the internal render target.
  22720. * If not width is applied, the render target is automatically resized.
  22721. *
  22722. * @type {?number}
  22723. * @default null
  22724. */
  22725. this.width = width;
  22726. /**
  22727. * The height of the internal render target.
  22728. *
  22729. * @type {?number}
  22730. * @default null
  22731. */
  22732. this.height = height;
  22733. /**
  22734. * The pixel ratio
  22735. *
  22736. * @type {number}
  22737. * @default 1
  22738. */
  22739. this.pixelRatio = 1;
  22740. /**
  22741. * The render target
  22742. *
  22743. * @type {RenderTarget}
  22744. */
  22745. this.renderTarget = renderTarget;
  22746. /**
  22747. * Whether the texture requires an update or not.
  22748. *
  22749. * @type {boolean}
  22750. * @default true
  22751. */
  22752. this.textureNeedsUpdate = true;
  22753. /**
  22754. * Whether the texture should automatically be updated or not.
  22755. *
  22756. * @type {boolean}
  22757. * @default true
  22758. */
  22759. this.autoUpdate = true;
  22760. /**
  22761. * The node which is used with the quad mesh for RTT.
  22762. *
  22763. * @private
  22764. * @type {Node}
  22765. * @default null
  22766. */
  22767. this._rttNode = null;
  22768. /**
  22769. * The internal quad mesh for RTT.
  22770. *
  22771. * @private
  22772. * @type {QuadMesh}
  22773. */
  22774. this._quadMesh = new QuadMesh( new NodeMaterial() );
  22775. /**
  22776. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  22777. * the texture once per render in its {@link RTTNode#updateBefore} method.
  22778. *
  22779. * @type {string}
  22780. * @default 'render'
  22781. */
  22782. this.updateBeforeType = NodeUpdateType.RENDER;
  22783. }
  22784. /**
  22785. * Whether the internal render target should automatically be resized or not.
  22786. *
  22787. * @type {boolean}
  22788. * @readonly
  22789. * @default true
  22790. */
  22791. get autoSize() {
  22792. return this.width === null;
  22793. }
  22794. setup( builder ) {
  22795. this._rttNode = this.node.context( builder.getSharedContext() );
  22796. this._quadMesh.material.name = 'RTT';
  22797. this._quadMesh.material.needsUpdate = true;
  22798. return super.setup( builder );
  22799. }
  22800. /**
  22801. * Sets the size of the internal render target
  22802. *
  22803. * @param {number} width - The width to set.
  22804. * @param {number} height - The width to set.
  22805. */
  22806. setSize( width, height ) {
  22807. this.width = width;
  22808. this.height = height;
  22809. const effectiveWidth = width * this.pixelRatio;
  22810. const effectiveHeight = height * this.pixelRatio;
  22811. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22812. this.textureNeedsUpdate = true;
  22813. }
  22814. /**
  22815. * Sets the pixel ratio. This will also resize the render target.
  22816. *
  22817. * @param {number} pixelRatio - The pixel ratio to set.
  22818. */
  22819. setPixelRatio( pixelRatio ) {
  22820. this.pixelRatio = pixelRatio;
  22821. this.setSize( this.width, this.height );
  22822. }
  22823. updateBefore( { renderer } ) {
  22824. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  22825. this.textureNeedsUpdate = false;
  22826. //
  22827. if ( this.autoSize === true ) {
  22828. this.pixelRatio = renderer.getPixelRatio();
  22829. const size = renderer.getSize( _size$1 );
  22830. this.setSize( size.width, size.height );
  22831. }
  22832. //
  22833. this._quadMesh.material.fragmentNode = this._rttNode;
  22834. //
  22835. const currentRenderTarget = renderer.getRenderTarget();
  22836. renderer.setRenderTarget( this.renderTarget );
  22837. this._quadMesh.render( renderer );
  22838. renderer.setRenderTarget( currentRenderTarget );
  22839. }
  22840. clone() {
  22841. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  22842. newNode.sampler = this.sampler;
  22843. newNode.referenceNode = this;
  22844. return newNode;
  22845. }
  22846. }
  22847. /**
  22848. * TSL function for creating a RTT node.
  22849. *
  22850. * @tsl
  22851. * @function
  22852. * @param {Node} node - The node to render a texture with.
  22853. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  22854. * @param {?number} [height=null] - The height of the internal render target.
  22855. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  22856. * @returns {RTTNode}
  22857. */
  22858. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  22859. /**
  22860. * TSL function for converting nodes to textures nodes.
  22861. *
  22862. * @tsl
  22863. * @function
  22864. * @param {Node} node - The node to render a texture with.
  22865. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  22866. * @param {?number} [height=null] - The height of the internal render target.
  22867. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  22868. * @returns {RTTNode}
  22869. */
  22870. const convertToTexture = ( node, ...params ) => {
  22871. if ( node.isTextureNode ) return node;
  22872. if ( node.isPassNode ) return node.getTextureNode();
  22873. return rtt( node, ...params );
  22874. };
  22875. /**
  22876. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  22877. * depth value and the camera's inverse projection matrix.
  22878. *
  22879. * @tsl
  22880. * @function
  22881. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  22882. * @param {Node<float>} depth - The fragment's depth value.
  22883. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  22884. * @return {Node<vec3>} The fragments position in view space.
  22885. */
  22886. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  22887. let clipSpacePosition;
  22888. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  22889. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  22890. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  22891. } else {
  22892. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  22893. }
  22894. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  22895. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  22896. } );
  22897. /**
  22898. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  22899. * and the camera's projection matrix
  22900. *
  22901. * @tsl
  22902. * @function
  22903. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  22904. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  22905. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  22906. */
  22907. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  22908. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  22909. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  22910. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  22911. } );
  22912. /**
  22913. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  22914. * target is available or if flat surface normals are required.
  22915. *
  22916. * @tsl
  22917. * @function
  22918. * @param {Node<vec2>} uv - The texture coordinate.
  22919. * @param {DepthTexture} depthTexture - The depth texture.
  22920. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  22921. * @return {Node<vec3>} The computed normal vector.
  22922. */
  22923. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  22924. const size = textureSize( textureLoad( depthTexture ) );
  22925. const p = ivec2( uv.mul( size ) ).toVar();
  22926. const c0 = textureLoad( depthTexture, p ).toVar();
  22927. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  22928. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  22929. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  22930. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  22931. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  22932. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  22933. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  22934. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  22935. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  22936. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  22937. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  22938. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  22939. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  22940. 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 ) ) );
  22941. 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 ) ) );
  22942. return normalize( cross( dpdx, dpdy ) );
  22943. } );
  22944. /**
  22945. * This special type of instanced buffer attribute is intended for compute shaders.
  22946. * In earlier three.js versions it was only possible to update attribute data
  22947. * on the CPU via JavaScript and then upload the data to the GPU. With the
  22948. * new material system and renderer it is now possible to use compute shaders
  22949. * to compute the data for an attribute more efficiently on the GPU.
  22950. *
  22951. * The idea is to create an instance of this class and provide it as an input
  22952. * to {@link StorageBufferNode}.
  22953. *
  22954. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  22955. *
  22956. * @augments InstancedBufferAttribute
  22957. */
  22958. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  22959. /**
  22960. * Constructs a new storage instanced buffer attribute.
  22961. *
  22962. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  22963. * The subsequent parameters are then obsolete.
  22964. * @param {number} itemSize - The item size.
  22965. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  22966. */
  22967. constructor( count, itemSize, typeClass = Float32Array ) {
  22968. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  22969. super( array, itemSize );
  22970. /**
  22971. * This flag can be used for type testing.
  22972. *
  22973. * @type {boolean}
  22974. * @readonly
  22975. * @default true
  22976. */
  22977. this.isStorageInstancedBufferAttribute = true;
  22978. }
  22979. }
  22980. /**
  22981. * This special type of buffer attribute is intended for compute shaders.
  22982. * In earlier three.js versions it was only possible to update attribute data
  22983. * on the CPU via JavaScript and then upload the data to the GPU. With the
  22984. * new material system and renderer it is now possible to use compute shaders
  22985. * to compute the data for an attribute more efficiently on the GPU.
  22986. *
  22987. * The idea is to create an instance of this class and provide it as an input
  22988. * to {@link StorageBufferNode}.
  22989. *
  22990. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  22991. *
  22992. * @augments BufferAttribute
  22993. */
  22994. class StorageBufferAttribute extends BufferAttribute {
  22995. /**
  22996. * Constructs a new storage buffer attribute.
  22997. *
  22998. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  22999. * The subsequent parameters are then obsolete.
  23000. * @param {number} itemSize - The item size.
  23001. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23002. */
  23003. constructor( count, itemSize, typeClass = Float32Array ) {
  23004. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23005. super( array, itemSize );
  23006. /**
  23007. * This flag can be used for type testing.
  23008. *
  23009. * @type {boolean}
  23010. * @readonly
  23011. * @default true
  23012. */
  23013. this.isStorageBufferAttribute = true;
  23014. }
  23015. }
  23016. /**
  23017. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  23018. *
  23019. * @tsl
  23020. * @function
  23021. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23022. * @param {string|Struct} [type='float'] - The data type.
  23023. * @returns {StorageBufferNode}
  23024. */
  23025. const attributeArray = ( count, type = 'float' ) => {
  23026. let itemSize, typedArray;
  23027. if ( type.isStruct === true ) {
  23028. itemSize = type.layout.getLength();
  23029. typedArray = getTypedArrayFromType( 'float' );
  23030. } else {
  23031. itemSize = getLengthFromType( type );
  23032. typedArray = getTypedArrayFromType( type );
  23033. }
  23034. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  23035. const node = storage( buffer, type, count );
  23036. return node;
  23037. };
  23038. /**
  23039. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  23040. *
  23041. * @tsl
  23042. * @function
  23043. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23044. * @param {string|Struct} [type='float'] - The data type.
  23045. * @returns {StorageBufferNode}
  23046. */
  23047. const instancedArray = ( count, type = 'float' ) => {
  23048. let itemSize, typedArray;
  23049. if ( type.isStruct === true ) {
  23050. itemSize = type.layout.getLength();
  23051. typedArray = getTypedArrayFromType( 'float' );
  23052. } else {
  23053. itemSize = getLengthFromType( type );
  23054. typedArray = getTypedArrayFromType( type );
  23055. }
  23056. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  23057. const node = storage( buffer, type, count );
  23058. return node;
  23059. };
  23060. /**
  23061. * A node for representing the uv coordinates of points.
  23062. *
  23063. * Can only be used with a WebGL backend. In WebGPU, point
  23064. * primitives always have the size of one pixel and can thus
  23065. * can't be used as sprite-like objects that display textures.
  23066. *
  23067. * @augments Node
  23068. */
  23069. class PointUVNode extends Node {
  23070. static get type() {
  23071. return 'PointUVNode';
  23072. }
  23073. /**
  23074. * Constructs a new point uv node.
  23075. */
  23076. constructor() {
  23077. super( 'vec2' );
  23078. /**
  23079. * This flag can be used for type testing.
  23080. *
  23081. * @type {boolean}
  23082. * @readonly
  23083. * @default true
  23084. */
  23085. this.isPointUVNode = true;
  23086. }
  23087. generate( /*builder*/ ) {
  23088. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  23089. }
  23090. }
  23091. /**
  23092. * TSL object that represents the uv coordinates of points.
  23093. *
  23094. * @tsl
  23095. * @type {PointUVNode}
  23096. */
  23097. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  23098. const _e1 = /*@__PURE__*/ new Euler();
  23099. const _m1 = /*@__PURE__*/ new Matrix4();
  23100. /**
  23101. * This module allows access to a collection of scene properties. The following predefined TSL objects
  23102. * are available for easier use:
  23103. *
  23104. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  23105. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  23106. * - `backgroundRotation`: A node that represents the scene's background rotation.
  23107. *
  23108. * @augments Node
  23109. */
  23110. class SceneNode extends Node {
  23111. static get type() {
  23112. return 'SceneNode';
  23113. }
  23114. /**
  23115. * Constructs a new scene node.
  23116. *
  23117. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  23118. * @param {?Scene} [scene=null] - A reference to the scene.
  23119. */
  23120. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  23121. super();
  23122. /**
  23123. * The scope defines the type of scene property that is accessed.
  23124. *
  23125. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  23126. */
  23127. this.scope = scope;
  23128. /**
  23129. * A reference to the scene that is going to be accessed.
  23130. *
  23131. * @type {?Scene}
  23132. * @default null
  23133. */
  23134. this.scene = scene;
  23135. }
  23136. /**
  23137. * Depending on the scope, the method returns a different type of node that represents
  23138. * the respective scene property.
  23139. *
  23140. * @param {NodeBuilder} builder - The current node builder.
  23141. * @return {Node} The output node.
  23142. */
  23143. setup( builder ) {
  23144. const scope = this.scope;
  23145. const scene = this.scene !== null ? this.scene : builder.scene;
  23146. let output;
  23147. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  23148. output = reference( 'backgroundBlurriness', 'float', scene );
  23149. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  23150. output = reference( 'backgroundIntensity', 'float', scene );
  23151. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  23152. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  23153. const background = scene.background;
  23154. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  23155. _e1.copy( scene.backgroundRotation );
  23156. // accommodate left-handed frame
  23157. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  23158. _m1.makeRotationFromEuler( _e1 );
  23159. } else {
  23160. _m1.identity();
  23161. }
  23162. return _m1;
  23163. } );
  23164. } else {
  23165. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  23166. }
  23167. return output;
  23168. }
  23169. }
  23170. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  23171. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  23172. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  23173. /**
  23174. * TSL object that represents the scene's background blurriness.
  23175. *
  23176. * @tsl
  23177. * @type {SceneNode}
  23178. */
  23179. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  23180. /**
  23181. * TSL object that represents the scene's background intensity.
  23182. *
  23183. * @tsl
  23184. * @type {SceneNode}
  23185. */
  23186. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  23187. /**
  23188. * TSL object that represents the scene's background rotation.
  23189. *
  23190. * @tsl
  23191. * @type {SceneNode}
  23192. */
  23193. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  23194. /**
  23195. * This special version of a texture node can be used to
  23196. * write data into a storage texture with a compute shader.
  23197. *
  23198. * ```js
  23199. * const storageTexture = new THREE.StorageTexture( width, height );
  23200. *
  23201. * const computeTexture = Fn( ( { storageTexture } ) => {
  23202. *
  23203. * const posX = instanceIndex.mod( width );
  23204. * const posY = instanceIndex.div( width );
  23205. * const indexUV = uvec2( posX, posY );
  23206. *
  23207. * // generate RGB values
  23208. *
  23209. * const r = 1;
  23210. * const g = 1;
  23211. * const b = 1;
  23212. *
  23213. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  23214. *
  23215. * } );
  23216. *
  23217. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  23218. * renderer.computeAsync( computeNode );
  23219. * ```
  23220. *
  23221. * This node can only be used with a WebGPU backend.
  23222. *
  23223. * @augments TextureNode
  23224. */
  23225. class StorageTextureNode extends TextureNode {
  23226. static get type() {
  23227. return 'StorageTextureNode';
  23228. }
  23229. /**
  23230. * Constructs a new storage texture node.
  23231. *
  23232. * @param {StorageTexture} value - The storage texture.
  23233. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23234. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23235. */
  23236. constructor( value, uvNode, storeNode = null ) {
  23237. super( value, uvNode );
  23238. /**
  23239. * The value node that should be stored in the texture.
  23240. *
  23241. * @type {?Node}
  23242. * @default null
  23243. */
  23244. this.storeNode = storeNode;
  23245. /**
  23246. * This flag can be used for type testing.
  23247. *
  23248. * @type {boolean}
  23249. * @readonly
  23250. * @default true
  23251. */
  23252. this.isStorageTextureNode = true;
  23253. /**
  23254. * The access type of the texture node.
  23255. *
  23256. * @type {string}
  23257. * @default 'writeOnly'
  23258. */
  23259. this.access = NodeAccess.WRITE_ONLY;
  23260. }
  23261. /**
  23262. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  23263. *
  23264. * @param {NodeBuilder} builder - The current node builder.
  23265. * @return {string} The input type.
  23266. */
  23267. getInputType( /*builder*/ ) {
  23268. return 'storageTexture';
  23269. }
  23270. setup( builder ) {
  23271. super.setup( builder );
  23272. const properties = builder.getNodeProperties( this );
  23273. properties.storeNode = this.storeNode;
  23274. }
  23275. /**
  23276. * Defines the node access.
  23277. *
  23278. * @param {string} value - The node access.
  23279. * @return {StorageTextureNode} A reference to this node.
  23280. */
  23281. setAccess( value ) {
  23282. this.access = value;
  23283. return this;
  23284. }
  23285. /**
  23286. * Generates the code snippet of the storage node. If no `storeNode`
  23287. * is defined, the texture node is generated as normal texture.
  23288. *
  23289. * @param {NodeBuilder} builder - The current node builder.
  23290. * @param {string} output - The current output.
  23291. * @return {string} The generated code snippet.
  23292. */
  23293. generate( builder, output ) {
  23294. let snippet;
  23295. if ( this.storeNode !== null ) {
  23296. snippet = this.generateStore( builder );
  23297. } else {
  23298. snippet = super.generate( builder, output );
  23299. }
  23300. return snippet;
  23301. }
  23302. /**
  23303. * Convenience method for configuring a read/write node access.
  23304. *
  23305. * @return {StorageTextureNode} A reference to this node.
  23306. */
  23307. toReadWrite() {
  23308. return this.setAccess( NodeAccess.READ_WRITE );
  23309. }
  23310. /**
  23311. * Convenience method for configuring a read-only node access.
  23312. *
  23313. * @return {StorageTextureNode} A reference to this node.
  23314. */
  23315. toReadOnly() {
  23316. return this.setAccess( NodeAccess.READ_ONLY );
  23317. }
  23318. /**
  23319. * Convenience method for configuring a write-only node access.
  23320. *
  23321. * @return {StorageTextureNode} A reference to this node.
  23322. */
  23323. toWriteOnly() {
  23324. return this.setAccess( NodeAccess.WRITE_ONLY );
  23325. }
  23326. /**
  23327. * Generates the code snippet of the storage texture node.
  23328. *
  23329. * @param {NodeBuilder} builder - The current node builder.
  23330. */
  23331. generateStore( builder ) {
  23332. const properties = builder.getNodeProperties( this );
  23333. const { uvNode, storeNode } = properties;
  23334. const textureProperty = super.generate( builder, 'property' );
  23335. const uvSnippet = uvNode.build( builder, 'uvec2' );
  23336. const storeSnippet = storeNode.build( builder, 'vec4' );
  23337. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  23338. builder.addLineFlowCode( snippet, this );
  23339. }
  23340. }
  23341. /**
  23342. * TSL function for creating a storage texture node.
  23343. *
  23344. * @tsl
  23345. * @function
  23346. * @param {StorageTexture} value - The storage texture.
  23347. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  23348. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23349. * @returns {StorageTextureNode}
  23350. */
  23351. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  23352. /**
  23353. * TODO: Explain difference to `storageTexture()`.
  23354. *
  23355. * @tsl
  23356. * @function
  23357. * @param {StorageTexture} value - The storage texture.
  23358. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23359. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23360. * @returns {StorageTextureNode}
  23361. */
  23362. const textureStore = ( value, uvNode, storeNode ) => {
  23363. const node = storageTexture( value, uvNode, storeNode );
  23364. if ( storeNode !== null ) node.toStack();
  23365. return node;
  23366. };
  23367. const normal = Fn( ( { texture, uv } ) => {
  23368. const epsilon = 0.0001;
  23369. const ret = vec3().toVar();
  23370. If( uv.x.lessThan( epsilon ), () => {
  23371. ret.assign( vec3( 1, 0, 0 ) );
  23372. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  23373. ret.assign( vec3( 0, 1, 0 ) );
  23374. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  23375. ret.assign( vec3( 0, 0, 1 ) );
  23376. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  23377. ret.assign( vec3( -1, 0, 0 ) );
  23378. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  23379. ret.assign( vec3( 0, -1, 0 ) );
  23380. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  23381. ret.assign( vec3( 0, 0, -1 ) );
  23382. } ).Else( () => {
  23383. const step = 0.01;
  23384. const x = texture.sample( uv.add( vec3( -0.01, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  23385. const y = texture.sample( uv.add( vec3( 0.0, -0.01, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  23386. const z = texture.sample( uv.add( vec3( 0.0, 0.0, -0.01 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  23387. ret.assign( vec3( x, y, z ) );
  23388. } );
  23389. return ret.normalize();
  23390. } );
  23391. /**
  23392. * This type of uniform node represents a 3D texture.
  23393. *
  23394. * @augments TextureNode
  23395. */
  23396. class Texture3DNode extends TextureNode {
  23397. static get type() {
  23398. return 'Texture3DNode';
  23399. }
  23400. /**
  23401. * Constructs a new 3D texture node.
  23402. *
  23403. * @param {Data3DTexture} value - The 3D texture.
  23404. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23405. * @param {?Node<int>} [levelNode=null] - The level node.
  23406. */
  23407. constructor( value, uvNode = null, levelNode = null ) {
  23408. super( value, uvNode, levelNode );
  23409. /**
  23410. * This flag can be used for type testing.
  23411. *
  23412. * @type {boolean}
  23413. * @readonly
  23414. * @default true
  23415. */
  23416. this.isTexture3DNode = true;
  23417. }
  23418. /**
  23419. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  23420. *
  23421. * @param {NodeBuilder} builder - The current node builder.
  23422. * @return {string} The input type.
  23423. */
  23424. getInputType( /*builder*/ ) {
  23425. return 'texture3D';
  23426. }
  23427. /**
  23428. * Returns a default uv node which is in context of 3D textures a three-dimensional
  23429. * uv node.
  23430. *
  23431. * @return {Node<vec3>} The default uv node.
  23432. */
  23433. getDefaultUV() {
  23434. return vec3( 0.5, 0.5, 0.5 );
  23435. }
  23436. /**
  23437. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  23438. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  23439. *
  23440. * @param {boolean} value - The update toggle.
  23441. */
  23442. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  23443. /**
  23444. * Overwrites the default implementation to return the unmodified uv node.
  23445. *
  23446. * @param {NodeBuilder} builder - The current node builder.
  23447. * @param {Node} uvNode - The uv node to setup.
  23448. * @return {Node} The unmodified uv node.
  23449. */
  23450. setupUV( builder, uvNode ) {
  23451. const texture = this.value;
  23452. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  23453. if ( this.sampler ) {
  23454. uvNode = uvNode.flipY();
  23455. } else {
  23456. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  23457. }
  23458. }
  23459. return uvNode;
  23460. }
  23461. /**
  23462. * Generates the uv code snippet.
  23463. *
  23464. * @param {NodeBuilder} builder - The current node builder.
  23465. * @param {Node} uvNode - The uv node to generate code for.
  23466. * @return {string} The generated code snippet.
  23467. */
  23468. generateUV( builder, uvNode ) {
  23469. return uvNode.build( builder, 'vec3' );
  23470. }
  23471. /**
  23472. * TODO.
  23473. *
  23474. * @param {Node<vec3>} uvNode - The uv node .
  23475. * @return {Node<vec3>} TODO.
  23476. */
  23477. normal( uvNode ) {
  23478. return normal( { texture: this, uv: uvNode } );
  23479. }
  23480. }
  23481. /**
  23482. * TSL function for creating a 3D texture node.
  23483. *
  23484. * @tsl
  23485. * @function
  23486. * @param {Data3DTexture} value - The 3D texture.
  23487. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23488. * @param {?Node<int>} [levelNode=null] - The level node.
  23489. * @returns {Texture3DNode}
  23490. */
  23491. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  23492. /**
  23493. * A special type of reference node that allows to link values in
  23494. * `userData` fields to node objects.
  23495. * ```js
  23496. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  23497. *
  23498. * const material = new THREE.SpriteNodeMaterial();
  23499. * material.rotationNode = userData( 'rotation', 'float' );
  23500. * ```
  23501. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  23502. * will automatically be updated when the `rotation` user data field changes.
  23503. *
  23504. * @augments ReferenceNode
  23505. */
  23506. class UserDataNode extends ReferenceNode {
  23507. static get type() {
  23508. return 'UserDataNode';
  23509. }
  23510. /**
  23511. * Constructs a new user data node.
  23512. *
  23513. * @param {string} property - The property name that should be referenced by the node.
  23514. * @param {string} inputType - The node data type of the reference.
  23515. * @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.
  23516. */
  23517. constructor( property, inputType, userData = null ) {
  23518. super( property, inputType, userData );
  23519. /**
  23520. * A reference to the `userData` object. If not provided, the `userData`
  23521. * property of the 3D object that uses the node material is evaluated.
  23522. *
  23523. * @type {?Object}
  23524. * @default null
  23525. */
  23526. this.userData = userData;
  23527. }
  23528. /**
  23529. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  23530. * `userData` field.
  23531. *
  23532. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  23533. * @return {Object} A reference to the `userData` field.
  23534. */
  23535. updateReference( state ) {
  23536. this.reference = this.userData !== null ? this.userData : state.object.userData;
  23537. return this.reference;
  23538. }
  23539. }
  23540. /**
  23541. * TSL function for creating a user data node.
  23542. *
  23543. * @tsl
  23544. * @function
  23545. * @param {string} name - The property name that should be referenced by the node.
  23546. * @param {string} inputType - The node data type of the reference.
  23547. * @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.
  23548. * @returns {UserDataNode}
  23549. */
  23550. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  23551. const _objectData = new WeakMap();
  23552. /**
  23553. * A node for representing motion or velocity vectors. Foundation
  23554. * for advanced post processing effects like motion blur or TRAA.
  23555. *
  23556. * The node keeps track of the model, view and projection matrices
  23557. * of the previous frame and uses them to compute offsets in NDC space.
  23558. * These offsets represent the final velocity.
  23559. *
  23560. * @augments TempNode
  23561. */
  23562. class VelocityNode extends TempNode {
  23563. static get type() {
  23564. return 'VelocityNode';
  23565. }
  23566. /**
  23567. * Constructs a new vertex color node.
  23568. */
  23569. constructor() {
  23570. super( 'vec2' );
  23571. /**
  23572. * The current projection matrix.
  23573. *
  23574. * @type {?Matrix4}
  23575. * @default null
  23576. */
  23577. this.projectionMatrix = null;
  23578. /**
  23579. * Overwritten since velocity nodes are updated per object.
  23580. *
  23581. * @type {string}
  23582. * @default 'object'
  23583. */
  23584. this.updateType = NodeUpdateType.OBJECT;
  23585. /**
  23586. * Overwritten since velocity nodes save data after the update.
  23587. *
  23588. * @type {string}
  23589. * @default 'object'
  23590. */
  23591. this.updateAfterType = NodeUpdateType.OBJECT;
  23592. /**
  23593. * Uniform node representing the previous model matrix in world space.
  23594. *
  23595. * @type {UniformNode<mat4>}
  23596. * @default null
  23597. */
  23598. this.previousModelWorldMatrix = uniform( new Matrix4() );
  23599. /**
  23600. * Uniform node representing the previous projection matrix.
  23601. *
  23602. * @type {UniformNode<mat4>}
  23603. * @default null
  23604. */
  23605. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  23606. /**
  23607. * Uniform node representing the previous view matrix.
  23608. *
  23609. * @type {UniformNode<mat4>}
  23610. * @default null
  23611. */
  23612. this.previousCameraViewMatrix = uniform( new Matrix4() );
  23613. }
  23614. /**
  23615. * Sets the given projection matrix.
  23616. *
  23617. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  23618. */
  23619. setProjectionMatrix( projectionMatrix ) {
  23620. this.projectionMatrix = projectionMatrix;
  23621. }
  23622. /**
  23623. * Updates velocity specific uniforms.
  23624. *
  23625. * @param {NodeFrame} frame - A reference to the current node frame.
  23626. */
  23627. update( { frameId, camera, object } ) {
  23628. const previousModelMatrix = getPreviousMatrix( object );
  23629. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  23630. //
  23631. const cameraData = getData( camera );
  23632. if ( cameraData.frameId !== frameId ) {
  23633. cameraData.frameId = frameId;
  23634. if ( cameraData.previousProjectionMatrix === undefined ) {
  23635. cameraData.previousProjectionMatrix = new Matrix4();
  23636. cameraData.previousCameraViewMatrix = new Matrix4();
  23637. cameraData.currentProjectionMatrix = new Matrix4();
  23638. cameraData.currentCameraViewMatrix = new Matrix4();
  23639. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23640. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  23641. } else {
  23642. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  23643. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  23644. }
  23645. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  23646. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  23647. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  23648. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  23649. }
  23650. }
  23651. /**
  23652. * Overwritten to updated velocity specific uniforms.
  23653. *
  23654. * @param {NodeFrame} frame - A reference to the current node frame.
  23655. */
  23656. updateAfter( { object } ) {
  23657. getPreviousMatrix( object ).copy( object.matrixWorld );
  23658. }
  23659. /**
  23660. * Implements the velocity computation based on the previous and current vertex data.
  23661. *
  23662. * @param {NodeBuilder} builder - A reference to the current node builder.
  23663. * @return {Node<vec2>} The motion vector.
  23664. */
  23665. setup( /*builder*/ ) {
  23666. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  23667. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  23668. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23669. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  23670. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  23671. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  23672. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  23673. return velocity;
  23674. }
  23675. }
  23676. function getData( object ) {
  23677. let objectData = _objectData.get( object );
  23678. if ( objectData === undefined ) {
  23679. objectData = {};
  23680. _objectData.set( object, objectData );
  23681. }
  23682. return objectData;
  23683. }
  23684. function getPreviousMatrix( object, index = 0 ) {
  23685. const objectData = getData( object );
  23686. let matrix = objectData[ index ];
  23687. if ( matrix === undefined ) {
  23688. objectData[ index ] = matrix = new Matrix4();
  23689. objectData[ index ].copy( object.matrixWorld );
  23690. }
  23691. return matrix;
  23692. }
  23693. /**
  23694. * TSL object that represents the velocity of a render pass.
  23695. *
  23696. * @tsl
  23697. * @type {VelocityNode}
  23698. */
  23699. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  23700. /**
  23701. * Represents a "Color Burn" blend mode.
  23702. *
  23703. * It's designed to darken the base layer's colors based on the color of the blend layer.
  23704. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  23705. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  23706. *
  23707. * @tsl
  23708. * @function
  23709. * @param {Node<vec3>} base - The base color.
  23710. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  23711. * @return {Node<vec3>} The result.
  23712. */
  23713. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23714. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  23715. } ).setLayout( {
  23716. name: 'blendBurn',
  23717. type: 'vec3',
  23718. inputs: [
  23719. { name: 'base', type: 'vec3' },
  23720. { name: 'blend', type: 'vec3' }
  23721. ]
  23722. } );
  23723. /**
  23724. * Represents a "Color Dodge" blend mode.
  23725. *
  23726. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  23727. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  23728. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  23729. *
  23730. * @tsl
  23731. * @function
  23732. * @param {Node<vec3>} base - The base color.
  23733. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23734. * @return {Node<vec3>} The result.
  23735. */
  23736. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23737. return min$1( base.div( blend.oneMinus() ), 1.0 );
  23738. } ).setLayout( {
  23739. name: 'blendDodge',
  23740. type: 'vec3',
  23741. inputs: [
  23742. { name: 'base', type: 'vec3' },
  23743. { name: 'blend', type: 'vec3' }
  23744. ]
  23745. } );
  23746. /**
  23747. * Represents a "Screen" blend mode.
  23748. *
  23749. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  23750. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  23751. * effects.
  23752. *
  23753. * @tsl
  23754. * @function
  23755. * @param {Node<vec3>} base - The base color.
  23756. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  23757. * @return {Node<vec3>} The result.
  23758. */
  23759. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23760. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  23761. } ).setLayout( {
  23762. name: 'blendScreen',
  23763. type: 'vec3',
  23764. inputs: [
  23765. { name: 'base', type: 'vec3' },
  23766. { name: 'blend', type: 'vec3' }
  23767. ]
  23768. } );
  23769. /**
  23770. * Represents a "Overlay" blend mode.
  23771. *
  23772. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  23773. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  23774. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  23775. *
  23776. * @tsl
  23777. * @function
  23778. * @param {Node<vec3>} base - The base color.
  23779. * @param {Node<vec3>} blend - The blend color
  23780. * @return {Node<vec3>} The result.
  23781. */
  23782. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23783. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  23784. } ).setLayout( {
  23785. name: 'blendOverlay',
  23786. type: 'vec3',
  23787. inputs: [
  23788. { name: 'base', type: 'vec3' },
  23789. { name: 'blend', type: 'vec3' }
  23790. ]
  23791. } );
  23792. /**
  23793. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  23794. * It assumes both input colors have non-premultiplied alpha.
  23795. *
  23796. * @tsl
  23797. * @function
  23798. * @param {Node<vec4>} base - The base color.
  23799. * @param {Node<vec4>} blend - The blend color
  23800. * @return {Node<vec4>} The result.
  23801. */
  23802. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  23803. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  23804. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  23805. } ).setLayout( {
  23806. name: 'blendColor',
  23807. type: 'vec4',
  23808. inputs: [
  23809. { name: 'base', type: 'vec4' },
  23810. { name: 'blend', type: 'vec4' }
  23811. ]
  23812. } );
  23813. // Deprecated
  23814. /**
  23815. * @tsl
  23816. * @function
  23817. * @deprecated since r171. Use {@link blendBurn} instead.
  23818. *
  23819. * @param {...any} params
  23820. * @returns {Function}
  23821. */
  23822. const burn = ( ...params ) => { // @deprecated, r171
  23823. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  23824. return blendBurn( params );
  23825. };
  23826. /**
  23827. * @tsl
  23828. * @function
  23829. * @deprecated since r171. Use {@link blendDodge} instead.
  23830. *
  23831. * @param {...any} params
  23832. * @returns {Function}
  23833. */
  23834. const dodge = ( ...params ) => { // @deprecated, r171
  23835. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  23836. return blendDodge( params );
  23837. };
  23838. /**
  23839. * @tsl
  23840. * @function
  23841. * @deprecated since r171. Use {@link blendScreen} instead.
  23842. *
  23843. * @param {...any} params
  23844. * @returns {Function}
  23845. */
  23846. const screen = ( ...params ) => { // @deprecated, r171
  23847. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  23848. return blendScreen( params );
  23849. };
  23850. /**
  23851. * @tsl
  23852. * @function
  23853. * @deprecated since r171. Use {@link blendOverlay} instead.
  23854. *
  23855. * @param {...any} params
  23856. * @returns {Function}
  23857. */
  23858. const overlay = ( ...params ) => { // @deprecated, r171
  23859. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  23860. return blendOverlay( params );
  23861. };
  23862. /**
  23863. * Computes a grayscale value for the given RGB color value.
  23864. *
  23865. * @tsl
  23866. * @function
  23867. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  23868. * @return {Node<vec3>} The grayscale color.
  23869. */
  23870. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  23871. return luminance( color.rgb );
  23872. } );
  23873. /**
  23874. * Super-saturates or desaturates the given RGB color.
  23875. *
  23876. * @tsl
  23877. * @function
  23878. * @param {Node<vec3>} color - The input color.
  23879. * @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.
  23880. * @return {Node<vec3>} The saturated color.
  23881. */
  23882. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23883. return adjustment.mix( luminance( color.rgb ), color.rgb );
  23884. } );
  23885. /**
  23886. * Selectively enhance the intensity of less saturated RGB colors. Can result
  23887. * in a more natural and visually appealing image with enhanced color depth
  23888. * compared to {@link ColorAdjustment#saturation}.
  23889. *
  23890. * @tsl
  23891. * @function
  23892. * @param {Node<vec3>} color - The input color.
  23893. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  23894. * @return {Node<vec3>} The updated color.
  23895. */
  23896. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23897. const average = add( color.r, color.g, color.b ).div( 3.0 );
  23898. const mx = color.r.max( color.g.max( color.b ) );
  23899. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  23900. return mix( color.rgb, mx, amt );
  23901. } );
  23902. /**
  23903. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  23904. *
  23905. * @tsl
  23906. * @function
  23907. * @param {Node<vec3>} color - The input color.
  23908. * @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.
  23909. * @return {Node<vec3>} The updated color.
  23910. */
  23911. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  23912. const k = vec3( 0.57735, 0.57735, 0.57735 );
  23913. const cosAngle = adjustment.cos();
  23914. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  23915. } );
  23916. /**
  23917. * Computes the luminance for the given RGB color value.
  23918. *
  23919. * @tsl
  23920. * @function
  23921. * @param {Node<vec3>} color - The color value to compute the luminance for.
  23922. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  23923. * @return {Node<vec3>} The luminance.
  23924. */
  23925. const luminance = (
  23926. color,
  23927. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  23928. ) => dot( color, luminanceCoefficients );
  23929. /**
  23930. * Color Decision List (CDL) v1.2
  23931. *
  23932. * Compact representation of color grading information, defined by slope, offset, power, and
  23933. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  23934. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  23935. *
  23936. * @tsl
  23937. * @function
  23938. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  23939. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  23940. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  23941. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  23942. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  23943. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  23944. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  23945. *
  23946. * References:
  23947. * - ASC CDL v1.2
  23948. * - {@link https://blender.stackexchange.com/a/55239/43930}
  23949. * - {@link https://docs.acescentral.com/specifications/acescc/}
  23950. */
  23951. const cdl = /*@__PURE__*/ Fn( ( [
  23952. color,
  23953. slope = vec3( 1 ),
  23954. offset = vec3( 0 ),
  23955. power = vec3( 1 ),
  23956. saturation = float( 1 ),
  23957. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  23958. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  23959. ] ) => {
  23960. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  23961. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  23962. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  23963. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  23964. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  23965. const pv = v.pow( power ).toVar();
  23966. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  23967. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  23968. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  23969. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  23970. return vec4( v.rgb, color.a );
  23971. } );
  23972. /**
  23973. * Represents a posterize effect which reduces the number of colors
  23974. * in an image, resulting in a more blocky and stylized appearance.
  23975. *
  23976. * @augments TempNode
  23977. */
  23978. class PosterizeNode extends TempNode {
  23979. static get type() {
  23980. return 'PosterizeNode';
  23981. }
  23982. /**
  23983. * Constructs a new posterize node.
  23984. *
  23985. * @param {Node} sourceNode - The input color.
  23986. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23987. */
  23988. constructor( sourceNode, stepsNode ) {
  23989. super();
  23990. /**
  23991. * The input color.
  23992. *
  23993. * @type {Node}
  23994. */
  23995. this.sourceNode = sourceNode;
  23996. /**
  23997. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  23998. *
  23999. * @type {Node}
  24000. */
  24001. this.stepsNode = stepsNode;
  24002. }
  24003. setup() {
  24004. const { sourceNode, stepsNode } = this;
  24005. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  24006. }
  24007. }
  24008. /**
  24009. * TSL function for creating a posterize node.
  24010. *
  24011. * @tsl
  24012. * @function
  24013. * @param {Node} sourceNode - The input color.
  24014. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24015. * @returns {PosterizeNode}
  24016. */
  24017. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  24018. const _size = /*@__PURE__*/ new Vector2();
  24019. /**
  24020. * Represents the texture of a pass node.
  24021. *
  24022. * @augments TextureNode
  24023. */
  24024. class PassTextureNode extends TextureNode {
  24025. static get type() {
  24026. return 'PassTextureNode';
  24027. }
  24028. /**
  24029. * Constructs a new pass texture node.
  24030. *
  24031. * @param {PassNode} passNode - The pass node.
  24032. * @param {Texture} texture - The output texture.
  24033. */
  24034. constructor( passNode, texture ) {
  24035. super( texture );
  24036. /**
  24037. * A reference to the pass node.
  24038. *
  24039. * @type {PassNode}
  24040. */
  24041. this.passNode = passNode;
  24042. this.setUpdateMatrix( false );
  24043. }
  24044. setup( builder ) {
  24045. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  24046. return super.setup( builder );
  24047. }
  24048. clone() {
  24049. return new this.constructor( this.passNode, this.value );
  24050. }
  24051. }
  24052. /**
  24053. * An extension of `PassTextureNode` which allows to manage more than one
  24054. * internal texture. Relevant for the `getPreviousTexture()` related API.
  24055. *
  24056. * @augments PassTextureNode
  24057. */
  24058. class PassMultipleTextureNode extends PassTextureNode {
  24059. static get type() {
  24060. return 'PassMultipleTextureNode';
  24061. }
  24062. /**
  24063. * Constructs a new pass texture node.
  24064. *
  24065. * @param {PassNode} passNode - The pass node.
  24066. * @param {string} textureName - The output texture name.
  24067. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  24068. */
  24069. constructor( passNode, textureName, previousTexture = false ) {
  24070. // null is passed to the super call since this class does not
  24071. // use an external texture for rendering pass data into. Instead
  24072. // the texture is managed by the pass node itself
  24073. super( passNode, null );
  24074. /**
  24075. * The output texture name.
  24076. *
  24077. * @type {string}
  24078. */
  24079. this.textureName = textureName;
  24080. /**
  24081. * Whether previous frame data should be used or not.
  24082. *
  24083. * @type {boolean}
  24084. */
  24085. this.previousTexture = previousTexture;
  24086. }
  24087. /**
  24088. * Updates the texture reference of this node.
  24089. */
  24090. updateTexture() {
  24091. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  24092. }
  24093. setup( builder ) {
  24094. this.updateTexture();
  24095. return super.setup( builder );
  24096. }
  24097. clone() {
  24098. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  24099. }
  24100. }
  24101. /**
  24102. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  24103. * This pass produces a render for the given scene and camera and can provide multiple outputs
  24104. * via MRT for further processing.
  24105. *
  24106. * ```js
  24107. * const postProcessing = new PostProcessing( renderer );
  24108. *
  24109. * const scenePass = pass( scene, camera );
  24110. *
  24111. * postProcessing.outputNode = scenePass;
  24112. * ```
  24113. *
  24114. * @augments TempNode
  24115. */
  24116. class PassNode extends TempNode {
  24117. static get type() {
  24118. return 'PassNode';
  24119. }
  24120. /**
  24121. * Constructs a new pass node.
  24122. *
  24123. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  24124. * @param {Scene} scene - A reference to the scene.
  24125. * @param {Camera} camera - A reference to the camera.
  24126. * @param {Object} options - Options for the internal render target.
  24127. */
  24128. constructor( scope, scene, camera, options = {} ) {
  24129. super( 'vec4' );
  24130. /**
  24131. * The scope of the pass. The scope determines whether the node outputs color or depth.
  24132. *
  24133. * @type {('color'|'depth')}
  24134. */
  24135. this.scope = scope;
  24136. /**
  24137. * A reference to the scene.
  24138. *
  24139. * @type {Scene}
  24140. */
  24141. this.scene = scene;
  24142. /**
  24143. * A reference to the camera.
  24144. *
  24145. * @type {Camera}
  24146. */
  24147. this.camera = camera;
  24148. /**
  24149. * Options for the internal render target.
  24150. *
  24151. * @type {Object}
  24152. */
  24153. this.options = options;
  24154. /**
  24155. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  24156. *
  24157. * @private
  24158. * @type {number}
  24159. * @default 1
  24160. */
  24161. this._pixelRatio = 1;
  24162. /**
  24163. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  24164. * @private
  24165. * @type {number}
  24166. * @default 1
  24167. */
  24168. this._width = 1;
  24169. /**
  24170. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  24171. * @private
  24172. * @type {number}
  24173. * @default 1
  24174. */
  24175. this._height = 1;
  24176. const depthTexture = new DepthTexture();
  24177. depthTexture.isRenderTargetTexture = true;
  24178. //depthTexture.type = FloatType;
  24179. depthTexture.name = 'depth';
  24180. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  24181. renderTarget.texture.name = 'output';
  24182. renderTarget.depthTexture = depthTexture;
  24183. /**
  24184. * The pass's render target.
  24185. *
  24186. * @type {RenderTarget}
  24187. */
  24188. this.renderTarget = renderTarget;
  24189. /**
  24190. * A dictionary holding the internal result textures.
  24191. *
  24192. * @private
  24193. * @type {Object<string, Texture>}
  24194. */
  24195. this._textures = {
  24196. output: renderTarget.texture,
  24197. depth: depthTexture
  24198. };
  24199. /**
  24200. * A dictionary holding the internal texture nodes.
  24201. *
  24202. * @private
  24203. * @type {Object<string, TextureNode>}
  24204. */
  24205. this._textureNodes = {};
  24206. /**
  24207. * A dictionary holding the internal depth nodes.
  24208. *
  24209. * @private
  24210. * @type {Object}
  24211. */
  24212. this._linearDepthNodes = {};
  24213. /**
  24214. * A dictionary holding the internal viewZ nodes.
  24215. *
  24216. * @private
  24217. * @type {Object}
  24218. */
  24219. this._viewZNodes = {};
  24220. /**
  24221. * A dictionary holding the texture data of the previous frame.
  24222. * Used for computing velocity/motion vectors.
  24223. *
  24224. * @private
  24225. * @type {Object<string, Texture>}
  24226. */
  24227. this._previousTextures = {};
  24228. /**
  24229. * A dictionary holding the texture nodes of the previous frame.
  24230. * Used for computing velocity/motion vectors.
  24231. *
  24232. * @private
  24233. * @type {Object<string, TextureNode>}
  24234. */
  24235. this._previousTextureNodes = {};
  24236. /**
  24237. * The `near` property of the camera as a uniform.
  24238. *
  24239. * @private
  24240. * @type {UniformNode}
  24241. */
  24242. this._cameraNear = uniform( 0 );
  24243. /**
  24244. * The `far` property of the camera as a uniform.
  24245. *
  24246. * @private
  24247. * @type {UniformNode}
  24248. */
  24249. this._cameraFar = uniform( 0 );
  24250. /**
  24251. * A MRT node configuring the MRT settings.
  24252. *
  24253. * @private
  24254. * @type {?MRTNode}
  24255. * @default null
  24256. */
  24257. this._mrt = null;
  24258. this._layers = null;
  24259. this._resolution = 1;
  24260. /**
  24261. * This flag can be used for type testing.
  24262. *
  24263. * @type {boolean}
  24264. * @readonly
  24265. * @default true
  24266. */
  24267. this.isPassNode = true;
  24268. /**
  24269. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  24270. * scene once per frame in its {@link PassNode#updateBefore} method.
  24271. *
  24272. * @type {string}
  24273. * @default 'frame'
  24274. */
  24275. this.updateBeforeType = NodeUpdateType.FRAME;
  24276. }
  24277. /**
  24278. * Sets the resolution for the pass.
  24279. * The resolution is a factor that is multiplied with the renderer's width and height.
  24280. *
  24281. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  24282. * @return {PassNode} A reference to this pass.
  24283. */
  24284. setResolution( resolution ) {
  24285. this._resolution = resolution;
  24286. return this;
  24287. }
  24288. /**
  24289. * Gets the current resolution of the pass.
  24290. *
  24291. * @return {number} The current resolution. A value of `1` means full resolution.
  24292. * @default 1
  24293. */
  24294. getResolution() {
  24295. return this._resolution;
  24296. }
  24297. setLayers( layers ) {
  24298. this._layers = layers;
  24299. return this;
  24300. }
  24301. getLayers() {
  24302. return this._layers;
  24303. }
  24304. /**
  24305. * Sets the given MRT node to setup MRT for this pass.
  24306. *
  24307. * @param {MRTNode} mrt - The MRT object.
  24308. * @return {PassNode} A reference to this pass.
  24309. */
  24310. setMRT( mrt ) {
  24311. this._mrt = mrt;
  24312. return this;
  24313. }
  24314. /**
  24315. * Returns the current MRT node.
  24316. *
  24317. * @return {MRTNode} The current MRT node.
  24318. */
  24319. getMRT() {
  24320. return this._mrt;
  24321. }
  24322. /**
  24323. * The method is overwritten so it always returns `true`.
  24324. *
  24325. * @return {boolean} Whether this node is global or not.
  24326. */
  24327. isGlobal() {
  24328. return true;
  24329. }
  24330. /**
  24331. * Returns the texture for the given output name.
  24332. *
  24333. * @param {string} name - The output name to get the texture for.
  24334. * @return {Texture} The texture.
  24335. */
  24336. getTexture( name ) {
  24337. let texture = this._textures[ name ];
  24338. if ( texture === undefined ) {
  24339. const refTexture = this.renderTarget.texture;
  24340. texture = refTexture.clone();
  24341. texture.name = name;
  24342. this._textures[ name ] = texture;
  24343. this.renderTarget.textures.push( texture );
  24344. }
  24345. return texture;
  24346. }
  24347. /**
  24348. * Returns the texture holding the data of the previous frame for the given output name.
  24349. *
  24350. * @param {string} name - The output name to get the texture for.
  24351. * @return {Texture} The texture holding the data of the previous frame.
  24352. */
  24353. getPreviousTexture( name ) {
  24354. let texture = this._previousTextures[ name ];
  24355. if ( texture === undefined ) {
  24356. texture = this.getTexture( name ).clone();
  24357. this._previousTextures[ name ] = texture;
  24358. }
  24359. return texture;
  24360. }
  24361. /**
  24362. * Switches current and previous textures for the given output name.
  24363. *
  24364. * @param {string} name - The output name.
  24365. */
  24366. toggleTexture( name ) {
  24367. const prevTexture = this._previousTextures[ name ];
  24368. if ( prevTexture !== undefined ) {
  24369. const texture = this._textures[ name ];
  24370. const index = this.renderTarget.textures.indexOf( texture );
  24371. this.renderTarget.textures[ index ] = prevTexture;
  24372. this._textures[ name ] = prevTexture;
  24373. this._previousTextures[ name ] = texture;
  24374. this._textureNodes[ name ].updateTexture();
  24375. this._previousTextureNodes[ name ].updateTexture();
  24376. }
  24377. }
  24378. /**
  24379. * Returns the texture node for the given output name.
  24380. *
  24381. * @param {string} [name='output'] - The output name to get the texture node for.
  24382. * @return {TextureNode} The texture node.
  24383. */
  24384. getTextureNode( name = 'output' ) {
  24385. let textureNode = this._textureNodes[ name ];
  24386. if ( textureNode === undefined ) {
  24387. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  24388. textureNode.updateTexture();
  24389. this._textureNodes[ name ] = textureNode;
  24390. }
  24391. return textureNode;
  24392. }
  24393. /**
  24394. * Returns the previous texture node for the given output name.
  24395. *
  24396. * @param {string} [name='output'] - The output name to get the previous texture node for.
  24397. * @return {TextureNode} The previous texture node.
  24398. */
  24399. getPreviousTextureNode( name = 'output' ) {
  24400. let textureNode = this._previousTextureNodes[ name ];
  24401. if ( textureNode === undefined ) {
  24402. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  24403. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  24404. textureNode.updateTexture();
  24405. this._previousTextureNodes[ name ] = textureNode;
  24406. }
  24407. return textureNode;
  24408. }
  24409. /**
  24410. * Returns a viewZ node of this pass.
  24411. *
  24412. * @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.
  24413. * @return {Node} The viewZ node.
  24414. */
  24415. getViewZNode( name = 'depth' ) {
  24416. let viewZNode = this._viewZNodes[ name ];
  24417. if ( viewZNode === undefined ) {
  24418. const cameraNear = this._cameraNear;
  24419. const cameraFar = this._cameraFar;
  24420. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  24421. }
  24422. return viewZNode;
  24423. }
  24424. /**
  24425. * Returns a linear depth node of this pass.
  24426. *
  24427. * @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.
  24428. * @return {Node} The linear depth node.
  24429. */
  24430. getLinearDepthNode( name = 'depth' ) {
  24431. let linearDepthNode = this._linearDepthNodes[ name ];
  24432. if ( linearDepthNode === undefined ) {
  24433. const cameraNear = this._cameraNear;
  24434. const cameraFar = this._cameraFar;
  24435. const viewZNode = this.getViewZNode( name );
  24436. // TODO: just if ( builder.camera.isPerspectiveCamera )
  24437. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  24438. }
  24439. return linearDepthNode;
  24440. }
  24441. setup( { renderer } ) {
  24442. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  24443. // TODO: Disable MSAA for WebGL backend for now
  24444. if ( renderer.backend.isWebGLBackend === true ) {
  24445. this.renderTarget.samples = 0;
  24446. }
  24447. this.renderTarget.texture.type = renderer.getColorBufferType();
  24448. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  24449. }
  24450. updateBefore( frame ) {
  24451. const { renderer } = frame;
  24452. const { scene } = this;
  24453. let camera;
  24454. let pixelRatio;
  24455. const outputRenderTarget = renderer.getOutputRenderTarget();
  24456. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  24457. pixelRatio = 1;
  24458. camera = renderer.xr.getCamera();
  24459. renderer.xr.updateCamera( camera );
  24460. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  24461. } else {
  24462. camera = this.camera;
  24463. pixelRatio = renderer.getPixelRatio();
  24464. renderer.getSize( _size );
  24465. }
  24466. this._pixelRatio = pixelRatio;
  24467. this.setSize( _size.width, _size.height );
  24468. const currentRenderTarget = renderer.getRenderTarget();
  24469. const currentMRT = renderer.getMRT();
  24470. const currentMask = camera.layers.mask;
  24471. this._cameraNear.value = camera.near;
  24472. this._cameraFar.value = camera.far;
  24473. if ( this._layers !== null ) {
  24474. camera.layers.mask = this._layers.mask;
  24475. }
  24476. for ( const name in this._previousTextures ) {
  24477. this.toggleTexture( name );
  24478. }
  24479. renderer.setRenderTarget( this.renderTarget );
  24480. renderer.setMRT( this._mrt );
  24481. renderer.render( scene, camera );
  24482. renderer.setRenderTarget( currentRenderTarget );
  24483. renderer.setMRT( currentMRT );
  24484. camera.layers.mask = currentMask;
  24485. }
  24486. /**
  24487. * Sets the size of the pass's render target. Honors the pixel ratio.
  24488. *
  24489. * @param {number} width - The width to set.
  24490. * @param {number} height - The height to set.
  24491. */
  24492. setSize( width, height ) {
  24493. this._width = width;
  24494. this._height = height;
  24495. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  24496. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  24497. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24498. }
  24499. /**
  24500. * Sets the pixel ratio the pass's render target and updates the size.
  24501. *
  24502. * @param {number} pixelRatio - The pixel ratio to set.
  24503. */
  24504. setPixelRatio( pixelRatio ) {
  24505. this._pixelRatio = pixelRatio;
  24506. this.setSize( this._width, this._height );
  24507. }
  24508. /**
  24509. * Frees internal resources. Should be called when the node is no longer in use.
  24510. */
  24511. dispose() {
  24512. this.renderTarget.dispose();
  24513. }
  24514. }
  24515. /**
  24516. * @static
  24517. * @type {'color'}
  24518. * @default 'color'
  24519. */
  24520. PassNode.COLOR = 'color';
  24521. /**
  24522. * @static
  24523. * @type {'depth'}
  24524. * @default 'depth'
  24525. */
  24526. PassNode.DEPTH = 'depth';
  24527. /**
  24528. * TSL function for creating a pass node.
  24529. *
  24530. * @tsl
  24531. * @function
  24532. * @param {Scene} scene - A reference to the scene.
  24533. * @param {Camera} camera - A reference to the camera.
  24534. * @param {Object} options - Options for the internal render target.
  24535. * @returns {PassNode}
  24536. */
  24537. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  24538. /**
  24539. * TSL function for creating a pass texture node.
  24540. *
  24541. * @tsl
  24542. * @function
  24543. * @param {PassNode} pass - The pass node.
  24544. * @param {Texture} texture - The output texture.
  24545. * @returns {PassTextureNode}
  24546. */
  24547. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  24548. /**
  24549. * TSL function for creating a depth pass node.
  24550. *
  24551. * @tsl
  24552. * @function
  24553. * @param {Scene} scene - A reference to the scene.
  24554. * @param {Camera} camera - A reference to the camera.
  24555. * @param {Object} options - Options for the internal render target.
  24556. * @returns {PassNode}
  24557. */
  24558. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  24559. /**
  24560. * Represents a render pass for producing a toon outline effect on compatible objects.
  24561. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  24562. * will receive the outline.
  24563. *
  24564. * ```js
  24565. * const postProcessing = new PostProcessing( renderer );
  24566. *
  24567. * const scenePass = toonOutlinePass( scene, camera );
  24568. *
  24569. * postProcessing.outputNode = scenePass;
  24570. * ```
  24571. * @augments PassNode
  24572. */
  24573. class ToonOutlinePassNode extends PassNode {
  24574. static get type() {
  24575. return 'ToonOutlinePassNode';
  24576. }
  24577. /**
  24578. * Constructs a new outline pass node.
  24579. *
  24580. * @param {Scene} scene - A reference to the scene.
  24581. * @param {Camera} camera - A reference to the camera.
  24582. * @param {Node} colorNode - Defines the outline's color.
  24583. * @param {Node} thicknessNode - Defines the outline's thickness.
  24584. * @param {Node} alphaNode - Defines the outline's alpha.
  24585. */
  24586. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  24587. super( PassNode.COLOR, scene, camera );
  24588. /**
  24589. * Defines the outline's color.
  24590. *
  24591. * @type {Node}
  24592. */
  24593. this.colorNode = colorNode;
  24594. /**
  24595. * Defines the outline's thickness.
  24596. *
  24597. * @type {Node}
  24598. */
  24599. this.thicknessNode = thicknessNode;
  24600. /**
  24601. * Defines the outline's alpha.
  24602. *
  24603. * @type {Node}
  24604. */
  24605. this.alphaNode = alphaNode;
  24606. /**
  24607. * An internal material cache.
  24608. *
  24609. * @private
  24610. * @type {WeakMap<Material, NodeMaterial>}
  24611. */
  24612. this._materialCache = new WeakMap();
  24613. }
  24614. updateBefore( frame ) {
  24615. const { renderer } = frame;
  24616. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  24617. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  24618. // only render outline for supported materials
  24619. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  24620. if ( material.wireframe === false ) {
  24621. const outlineMaterial = this._getOutlineMaterial( material );
  24622. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  24623. }
  24624. }
  24625. // default
  24626. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  24627. } );
  24628. super.updateBefore( frame );
  24629. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  24630. }
  24631. /**
  24632. * Creates the material used for outline rendering.
  24633. *
  24634. * @private
  24635. * @return {NodeMaterial} The outline material.
  24636. */
  24637. _createMaterial() {
  24638. const material = new NodeMaterial();
  24639. material.isMeshToonOutlineMaterial = true;
  24640. material.name = 'Toon_Outline';
  24641. material.side = BackSide;
  24642. // vertex node
  24643. const outlineNormal = normalLocal.negate();
  24644. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  24645. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  24646. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  24647. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  24648. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  24649. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  24650. // color node
  24651. material.colorNode = vec4( this.colorNode, this.alphaNode );
  24652. return material;
  24653. }
  24654. /**
  24655. * For the given toon material, this method returns a corresponding
  24656. * outline material.
  24657. *
  24658. * @private
  24659. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  24660. * @return {NodeMaterial} The outline material.
  24661. */
  24662. _getOutlineMaterial( originalMaterial ) {
  24663. let outlineMaterial = this._materialCache.get( originalMaterial );
  24664. if ( outlineMaterial === undefined ) {
  24665. outlineMaterial = this._createMaterial();
  24666. this._materialCache.set( originalMaterial, outlineMaterial );
  24667. }
  24668. return outlineMaterial;
  24669. }
  24670. }
  24671. /**
  24672. * TSL function for creating a toon outline pass node.
  24673. *
  24674. * @tsl
  24675. * @function
  24676. * @param {Scene} scene - A reference to the scene.
  24677. * @param {Camera} camera - A reference to the camera.
  24678. * @param {Color} color - Defines the outline's color.
  24679. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  24680. * @param {number} [alpha=1] - Defines the outline's alpha.
  24681. * @returns {ToonOutlinePassNode}
  24682. */
  24683. 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 ) ) );
  24684. /**
  24685. * Linear tone mapping, exposure only.
  24686. *
  24687. * @tsl
  24688. * @function
  24689. * @param {Node<vec3>} color - The color that should be tone mapped.
  24690. * @param {Node<float>} exposure - The exposure.
  24691. * @return {Node<vec3>} The tone mapped color.
  24692. */
  24693. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24694. return color.mul( exposure ).clamp();
  24695. } ).setLayout( {
  24696. name: 'linearToneMapping',
  24697. type: 'vec3',
  24698. inputs: [
  24699. { name: 'color', type: 'vec3' },
  24700. { name: 'exposure', type: 'float' }
  24701. ]
  24702. } );
  24703. /**
  24704. * Reinhard tone mapping.
  24705. *
  24706. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  24707. *
  24708. * @tsl
  24709. * @function
  24710. * @param {Node<vec3>} color - The color that should be tone mapped.
  24711. * @param {Node<float>} exposure - The exposure.
  24712. * @return {Node<vec3>} The tone mapped color.
  24713. */
  24714. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24715. color = color.mul( exposure );
  24716. return color.div( color.add( 1.0 ) ).clamp();
  24717. } ).setLayout( {
  24718. name: 'reinhardToneMapping',
  24719. type: 'vec3',
  24720. inputs: [
  24721. { name: 'color', type: 'vec3' },
  24722. { name: 'exposure', type: 'float' }
  24723. ]
  24724. } );
  24725. /**
  24726. * Cineon tone mapping.
  24727. *
  24728. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  24729. *
  24730. * @tsl
  24731. * @function
  24732. * @param {Node<vec3>} color - The color that should be tone mapped.
  24733. * @param {Node<float>} exposure - The exposure.
  24734. * @return {Node<vec3>} The tone mapped color.
  24735. */
  24736. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24737. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  24738. color = color.mul( exposure );
  24739. color = color.sub( 0.004 ).max( 0.0 );
  24740. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  24741. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  24742. return a.div( b ).pow( 2.2 );
  24743. } ).setLayout( {
  24744. name: 'cineonToneMapping',
  24745. type: 'vec3',
  24746. inputs: [
  24747. { name: 'color', type: 'vec3' },
  24748. { name: 'exposure', type: 'float' }
  24749. ]
  24750. } );
  24751. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  24752. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24753. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  24754. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  24755. return a.div( b );
  24756. } );
  24757. /**
  24758. * ACESFilmic tone mapping.
  24759. *
  24760. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  24761. *
  24762. * @tsl
  24763. * @function
  24764. * @param {Node<vec3>} color - The color that should be tone mapped.
  24765. * @param {Node<float>} exposure - The exposure.
  24766. * @return {Node<vec3>} The tone mapped color.
  24767. */
  24768. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24769. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  24770. const ACESInputMat = mat3(
  24771. 0.59719, 0.35458, 0.04823,
  24772. 0.07600, 0.90834, 0.01566,
  24773. 0.02840, 0.13383, 0.83777
  24774. );
  24775. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  24776. const ACESOutputMat = mat3(
  24777. 1.60475, -0.53108, -0.07367,
  24778. -0.10208, 1.10813, -605e-5,
  24779. -327e-5, -0.07276, 1.07602
  24780. );
  24781. color = color.mul( exposure ).div( 0.6 );
  24782. color = ACESInputMat.mul( color );
  24783. // Apply RRT and ODT
  24784. color = RRTAndODTFit( color );
  24785. color = ACESOutputMat.mul( color );
  24786. // Clamp to [0, 1]
  24787. return color.clamp();
  24788. } ).setLayout( {
  24789. name: 'acesFilmicToneMapping',
  24790. type: 'vec3',
  24791. inputs: [
  24792. { name: 'color', type: 'vec3' },
  24793. { name: 'exposure', type: 'float' }
  24794. ]
  24795. } );
  24796. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, -0.1246, -0.0182 ), vec3( -0.5876, 1.1329, -0.1006 ), vec3( -0.0728, -83e-4, 1.1187 ) );
  24797. 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 ) );
  24798. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  24799. const x = vec3( x_immutable ).toVar();
  24800. const x2 = vec3( x.mul( x ) ).toVar();
  24801. const x4 = vec3( x2.mul( x2 ) ).toVar();
  24802. 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 ) ) ) );
  24803. } );
  24804. /**
  24805. * AgX tone mapping.
  24806. *
  24807. * @tsl
  24808. * @function
  24809. * @param {Node<vec3>} color - The color that should be tone mapped.
  24810. * @param {Node<float>} exposure - The exposure.
  24811. * @return {Node<vec3>} The tone mapped color.
  24812. */
  24813. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24814. const colortone = vec3( color ).toVar();
  24815. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  24816. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  24817. const AgxMinEv = float( -12.47393 );
  24818. const AgxMaxEv = float( 4.026069 );
  24819. colortone.mulAssign( exposure );
  24820. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  24821. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  24822. colortone.assign( max$1( colortone, 1e-10 ) );
  24823. colortone.assign( log2( colortone ) );
  24824. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  24825. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  24826. colortone.assign( agxDefaultContrastApprox( colortone ) );
  24827. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  24828. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  24829. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  24830. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  24831. return colortone;
  24832. } ).setLayout( {
  24833. name: 'agxToneMapping',
  24834. type: 'vec3',
  24835. inputs: [
  24836. { name: 'color', type: 'vec3' },
  24837. { name: 'exposure', type: 'float' }
  24838. ]
  24839. } );
  24840. /**
  24841. * Neutral tone mapping.
  24842. *
  24843. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  24844. *
  24845. * @tsl
  24846. * @function
  24847. * @param {Node<vec3>} color - The color that should be tone mapped.
  24848. * @param {Node<float>} exposure - The exposure.
  24849. * @return {Node<vec3>} The tone mapped color.
  24850. */
  24851. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  24852. const StartCompression = float( 0.8 - 0.04 );
  24853. const Desaturation = float( 0.15 );
  24854. color = color.mul( exposure );
  24855. const x = min$1( color.r, min$1( color.g, color.b ) );
  24856. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  24857. color.subAssign( offset );
  24858. const peak = max$1( color.r, max$1( color.g, color.b ) );
  24859. If( peak.lessThan( StartCompression ), () => {
  24860. return color;
  24861. } );
  24862. const d = sub( 1, StartCompression );
  24863. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  24864. color.mulAssign( newPeak.div( peak ) );
  24865. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  24866. return mix( color, vec3( newPeak ), g );
  24867. } ).setLayout( {
  24868. name: 'neutralToneMapping',
  24869. type: 'vec3',
  24870. inputs: [
  24871. { name: 'color', type: 'vec3' },
  24872. { name: 'exposure', type: 'float' }
  24873. ]
  24874. } );
  24875. /**
  24876. * This class represents native code sections. It is the base
  24877. * class for modules like {@link FunctionNode} which allows to implement
  24878. * functions with native shader languages.
  24879. *
  24880. * @augments Node
  24881. */
  24882. class CodeNode extends Node {
  24883. static get type() {
  24884. return 'CodeNode';
  24885. }
  24886. /**
  24887. * Constructs a new code node.
  24888. *
  24889. * @param {string} [code=''] - The native code.
  24890. * @param {Array<Node>} [includes=[]] - An array of includes.
  24891. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24892. */
  24893. constructor( code = '', includes = [], language = '' ) {
  24894. super( 'code' );
  24895. /**
  24896. * This flag can be used for type testing.
  24897. *
  24898. * @type {boolean}
  24899. * @readonly
  24900. * @default true
  24901. */
  24902. this.isCodeNode = true;
  24903. /**
  24904. * The native code.
  24905. *
  24906. * @type {string}
  24907. * @default ''
  24908. */
  24909. this.code = code;
  24910. /**
  24911. * An array of includes
  24912. *
  24913. * @type {Array<Node>}
  24914. * @default []
  24915. */
  24916. this.includes = includes;
  24917. /**
  24918. * The used language.
  24919. *
  24920. * @type {('js'|'wgsl'|'glsl')}
  24921. * @default ''
  24922. */
  24923. this.language = language;
  24924. }
  24925. /**
  24926. * The method is overwritten so it always returns `true`.
  24927. *
  24928. * @return {boolean} Whether this node is global or not.
  24929. */
  24930. isGlobal() {
  24931. return true;
  24932. }
  24933. /**
  24934. * Sets the includes of this code node.
  24935. *
  24936. * @param {Array<Node>} includes - The includes to set.
  24937. * @return {CodeNode} A reference to this node.
  24938. */
  24939. setIncludes( includes ) {
  24940. this.includes = includes;
  24941. return this;
  24942. }
  24943. /**
  24944. * Returns the includes of this code node.
  24945. *
  24946. * @param {NodeBuilder} builder - The current node builder.
  24947. * @return {Array<Node>} The includes.
  24948. */
  24949. getIncludes( /*builder*/ ) {
  24950. return this.includes;
  24951. }
  24952. generate( builder ) {
  24953. const includes = this.getIncludes( builder );
  24954. for ( const include of includes ) {
  24955. include.build( builder );
  24956. }
  24957. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  24958. nodeCode.code = this.code;
  24959. return nodeCode.code;
  24960. }
  24961. serialize( data ) {
  24962. super.serialize( data );
  24963. data.code = this.code;
  24964. data.language = this.language;
  24965. }
  24966. deserialize( data ) {
  24967. super.deserialize( data );
  24968. this.code = data.code;
  24969. this.language = data.language;
  24970. }
  24971. }
  24972. /**
  24973. * TSL function for creating a code node.
  24974. *
  24975. * @tsl
  24976. * @function
  24977. * @param {string} [code] - The native code.
  24978. * @param {?Array<Node>} [includes=[]] - An array of includes.
  24979. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  24980. * @returns {CodeNode}
  24981. */
  24982. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  24983. /**
  24984. * TSL function for creating a JS code node.
  24985. *
  24986. * @tsl
  24987. * @function
  24988. * @param {string} src - The native code.
  24989. * @param {Array<Node>} includes - An array of includes.
  24990. * @returns {CodeNode}
  24991. */
  24992. const js = ( src, includes ) => code( src, includes, 'js' );
  24993. /**
  24994. * TSL function for creating a WGSL code node.
  24995. *
  24996. * @tsl
  24997. * @function
  24998. * @param {string} src - The native code.
  24999. * @param {Array<Node>} includes - An array of includes.
  25000. * @returns {CodeNode}
  25001. */
  25002. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  25003. /**
  25004. * TSL function for creating a GLSL code node.
  25005. *
  25006. * @tsl
  25007. * @function
  25008. * @param {string} src - The native code.
  25009. * @param {Array<Node>} includes - An array of includes.
  25010. * @returns {CodeNode}
  25011. */
  25012. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  25013. /**
  25014. * This class represents a native shader function. It can be used to implement
  25015. * certain aspects of a node material with native shader code. There are two predefined
  25016. * TSL functions for easier usage.
  25017. *
  25018. * - `wgslFn`: Creates a WGSL function node.
  25019. * - `glslFn`: Creates a GLSL function node.
  25020. *
  25021. * A basic example with one include looks like so:
  25022. *
  25023. * ```js
  25024. * const desaturateWGSLFn = wgslFn( `
  25025. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  25026. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  25027. * return vec3<f32>( dot( lum, color ) );
  25028. * }`
  25029. *);
  25030. * const someWGSLFn = wgslFn( `
  25031. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  25032. * return desaturate( color );
  25033. * }
  25034. * `, [ desaturateWGSLFn ] );
  25035. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  25036. *```
  25037. * @augments CodeNode
  25038. */
  25039. class FunctionNode extends CodeNode {
  25040. static get type() {
  25041. return 'FunctionNode';
  25042. }
  25043. /**
  25044. * Constructs a new function node.
  25045. *
  25046. * @param {string} [code=''] - The native code.
  25047. * @param {Array<Node>} [includes=[]] - An array of includes.
  25048. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25049. */
  25050. constructor( code = '', includes = [], language = '' ) {
  25051. super( code, includes, language );
  25052. }
  25053. getNodeType( builder ) {
  25054. return this.getNodeFunction( builder ).type;
  25055. }
  25056. /**
  25057. * Returns the inputs of this function node.
  25058. *
  25059. * @param {NodeBuilder} builder - The current node builder.
  25060. * @return {Array<NodeFunctionInput>} The inputs.
  25061. */
  25062. getInputs( builder ) {
  25063. return this.getNodeFunction( builder ).inputs;
  25064. }
  25065. /**
  25066. * Returns the node function for this function node.
  25067. *
  25068. * @param {NodeBuilder} builder - The current node builder.
  25069. * @return {NodeFunction} The node function.
  25070. */
  25071. getNodeFunction( builder ) {
  25072. const nodeData = builder.getDataFromNode( this );
  25073. let nodeFunction = nodeData.nodeFunction;
  25074. if ( nodeFunction === undefined ) {
  25075. nodeFunction = builder.parser.parseFunction( this.code );
  25076. nodeData.nodeFunction = nodeFunction;
  25077. }
  25078. return nodeFunction;
  25079. }
  25080. generate( builder, output ) {
  25081. super.generate( builder );
  25082. const nodeFunction = this.getNodeFunction( builder );
  25083. const name = nodeFunction.name;
  25084. const type = nodeFunction.type;
  25085. const nodeCode = builder.getCodeFromNode( this, type );
  25086. if ( name !== '' ) {
  25087. // use a custom property name
  25088. nodeCode.name = name;
  25089. }
  25090. const propertyName = builder.getPropertyName( nodeCode );
  25091. const code = this.getNodeFunction( builder ).getCode( propertyName );
  25092. nodeCode.code = code + '\n';
  25093. if ( output === 'property' ) {
  25094. return propertyName;
  25095. } else {
  25096. return builder.format( `${ propertyName }()`, type, output );
  25097. }
  25098. }
  25099. }
  25100. const nativeFn = ( code, includes = [], language = '' ) => {
  25101. for ( let i = 0; i < includes.length; i ++ ) {
  25102. const include = includes[ i ];
  25103. // TSL Function: glslFn, wgslFn
  25104. if ( typeof include === 'function' ) {
  25105. includes[ i ] = include.functionNode;
  25106. }
  25107. }
  25108. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  25109. const fn = ( ...params ) => functionNode.call( ...params );
  25110. fn.functionNode = functionNode;
  25111. return fn;
  25112. };
  25113. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  25114. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  25115. /**
  25116. * `ScriptableNode` uses this class to manage script inputs and outputs.
  25117. *
  25118. * @augments Node
  25119. */
  25120. class ScriptableValueNode extends Node {
  25121. static get type() {
  25122. return 'ScriptableValueNode';
  25123. }
  25124. /**
  25125. * Constructs a new scriptable node.
  25126. *
  25127. * @param {any} [value=null] - The value.
  25128. */
  25129. constructor( value = null ) {
  25130. super();
  25131. /**
  25132. * A reference to the value.
  25133. *
  25134. * @private
  25135. * @default null
  25136. */
  25137. this._value = value;
  25138. /**
  25139. * Depending on the type of `_value`, this property might cache parsed data.
  25140. *
  25141. * @private
  25142. * @default null
  25143. */
  25144. this._cache = null;
  25145. /**
  25146. * If this node represents an input, this property represents the input type.
  25147. *
  25148. * @type {?string}
  25149. * @default null
  25150. */
  25151. this.inputType = null;
  25152. /**
  25153. * If this node represents an output, this property represents the output type.
  25154. *
  25155. * @type {?string}
  25156. * @default null
  25157. */
  25158. this.outputType = null;
  25159. /**
  25160. * An event dispatcher for managing events.
  25161. *
  25162. * @type {EventDispatcher}
  25163. */
  25164. this.events = new EventDispatcher();
  25165. /**
  25166. * This flag can be used for type testing.
  25167. *
  25168. * @type {boolean}
  25169. * @readonly
  25170. * @default true
  25171. */
  25172. this.isScriptableValueNode = true;
  25173. }
  25174. /**
  25175. * Whether this node represents an output or not.
  25176. *
  25177. * @type {boolean}
  25178. * @readonly
  25179. * @default true
  25180. */
  25181. get isScriptableOutputNode() {
  25182. return this.outputType !== null;
  25183. }
  25184. set value( val ) {
  25185. if ( this._value === val ) return;
  25186. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  25187. URL.revokeObjectURL( this._cache );
  25188. this._cache = null;
  25189. }
  25190. this._value = val;
  25191. this.events.dispatchEvent( { type: 'change' } );
  25192. this.refresh();
  25193. }
  25194. /**
  25195. * The node's value.
  25196. *
  25197. * @type {any}
  25198. */
  25199. get value() {
  25200. return this._value;
  25201. }
  25202. /**
  25203. * Dispatches the `refresh` event.
  25204. */
  25205. refresh() {
  25206. this.events.dispatchEvent( { type: 'refresh' } );
  25207. }
  25208. /**
  25209. * The `value` property usually represents a node or even binary data in form of array buffers.
  25210. * In this case, this method tries to return the actual value behind the complex type.
  25211. *
  25212. * @return {any} The value.
  25213. */
  25214. getValue() {
  25215. const value = this.value;
  25216. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  25217. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  25218. } else if ( value && value.value !== null && value.value !== undefined && (
  25219. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  25220. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  25221. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  25222. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  25223. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  25224. ( this.inputType === 'Color' && value.value.isColor ) ||
  25225. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  25226. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  25227. ) ) {
  25228. return value.value;
  25229. }
  25230. return this._cache || value;
  25231. }
  25232. /**
  25233. * Overwritten since the node type is inferred from the value.
  25234. *
  25235. * @param {NodeBuilder} builder - The current node builder.
  25236. * @return {string} The node type.
  25237. */
  25238. getNodeType( builder ) {
  25239. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  25240. }
  25241. setup() {
  25242. return this.value && this.value.isNode ? this.value : float();
  25243. }
  25244. serialize( data ) {
  25245. super.serialize( data );
  25246. if ( this.value !== null ) {
  25247. if ( this.inputType === 'ArrayBuffer' ) {
  25248. data.value = arrayBufferToBase64( this.value );
  25249. } else {
  25250. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  25251. }
  25252. } else {
  25253. data.value = null;
  25254. }
  25255. data.inputType = this.inputType;
  25256. data.outputType = this.outputType;
  25257. }
  25258. deserialize( data ) {
  25259. super.deserialize( data );
  25260. let value = null;
  25261. if ( data.value !== null ) {
  25262. if ( data.inputType === 'ArrayBuffer' ) {
  25263. value = base64ToArrayBuffer( data.value );
  25264. } else if ( data.inputType === 'Texture' ) {
  25265. value = data.meta.textures[ data.value ];
  25266. } else {
  25267. value = data.meta.nodes[ data.value ] || null;
  25268. }
  25269. }
  25270. this.value = value;
  25271. this.inputType = data.inputType;
  25272. this.outputType = data.outputType;
  25273. }
  25274. }
  25275. /**
  25276. * TSL function for creating a scriptable value node.
  25277. *
  25278. * @tsl
  25279. * @function
  25280. * @param {any} [value] - The value.
  25281. * @returns {ScriptableValueNode}
  25282. */
  25283. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  25284. /**
  25285. * A Map-like data structure for managing resources of scriptable nodes.
  25286. *
  25287. * @augments Map
  25288. */
  25289. class Resources extends Map {
  25290. get( key, callback = null, ...params ) {
  25291. if ( this.has( key ) ) return super.get( key );
  25292. if ( callback !== null ) {
  25293. const value = callback( ...params );
  25294. this.set( key, value );
  25295. return value;
  25296. }
  25297. }
  25298. }
  25299. class Parameters {
  25300. constructor( scriptableNode ) {
  25301. this.scriptableNode = scriptableNode;
  25302. }
  25303. get parameters() {
  25304. return this.scriptableNode.parameters;
  25305. }
  25306. get layout() {
  25307. return this.scriptableNode.getLayout();
  25308. }
  25309. getInputLayout( id ) {
  25310. return this.scriptableNode.getInputLayout( id );
  25311. }
  25312. get( name ) {
  25313. const param = this.parameters[ name ];
  25314. const value = param ? param.getValue() : null;
  25315. return value;
  25316. }
  25317. }
  25318. /**
  25319. * Defines the resources (e.g. namespaces) of scriptable nodes.
  25320. *
  25321. * @type {Resources}
  25322. */
  25323. const ScriptableNodeResources = new Resources();
  25324. /**
  25325. * This type of node allows to implement nodes with custom scripts. The script
  25326. * section is represented as an instance of `CodeNode` written with JavaScript.
  25327. * The script itself must adhere to a specific structure.
  25328. *
  25329. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  25330. * - layout: The layout object defines the script's interface (inputs and outputs).
  25331. *
  25332. * ```js
  25333. * ScriptableNodeResources.set( 'TSL', TSL );
  25334. *
  25335. * const scriptableNode = scriptable( js( `
  25336. * layout = {
  25337. * outputType: 'node',
  25338. * elements: [
  25339. * { name: 'source', inputType: 'node' },
  25340. * ]
  25341. * };
  25342. *
  25343. * const { mul, oscSine } = TSL;
  25344. *
  25345. * function main() {
  25346. * const source = parameters.get( 'source' ) || float();
  25347. * return mul( source, oscSine() ) );
  25348. * }
  25349. *
  25350. * ` ) );
  25351. *
  25352. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  25353. *
  25354. * const material = new THREE.MeshBasicNodeMaterial();
  25355. * material.colorNode = scriptableNode;
  25356. * ```
  25357. *
  25358. * @augments Node
  25359. */
  25360. class ScriptableNode extends Node {
  25361. static get type() {
  25362. return 'ScriptableNode';
  25363. }
  25364. /**
  25365. * Constructs a new scriptable node.
  25366. *
  25367. * @param {?CodeNode} [codeNode=null] - The code node.
  25368. * @param {Object} [parameters={}] - The parameters definition.
  25369. */
  25370. constructor( codeNode = null, parameters = {} ) {
  25371. super();
  25372. /**
  25373. * The code node.
  25374. *
  25375. * @type {?CodeNode}
  25376. * @default null
  25377. */
  25378. this.codeNode = codeNode;
  25379. /**
  25380. * The parameters definition.
  25381. *
  25382. * @type {Object}
  25383. * @default {}
  25384. */
  25385. this.parameters = parameters;
  25386. this._local = new Resources();
  25387. this._output = scriptableValue( null );
  25388. this._outputs = {};
  25389. this._source = this.source;
  25390. this._method = null;
  25391. this._object = null;
  25392. this._value = null;
  25393. this._needsOutputUpdate = true;
  25394. this.onRefresh = this.onRefresh.bind( this );
  25395. /**
  25396. * This flag can be used for type testing.
  25397. *
  25398. * @type {boolean}
  25399. * @readonly
  25400. * @default true
  25401. */
  25402. this.isScriptableNode = true;
  25403. }
  25404. /**
  25405. * The source code of the scriptable node.
  25406. *
  25407. * @type {string}
  25408. */
  25409. get source() {
  25410. return this.codeNode ? this.codeNode.code : '';
  25411. }
  25412. /**
  25413. * Sets the reference of a local script variable.
  25414. *
  25415. * @param {string} name - The variable name.
  25416. * @param {Object} value - The reference to set.
  25417. * @return {Resources} The resource map
  25418. */
  25419. setLocal( name, value ) {
  25420. return this._local.set( name, value );
  25421. }
  25422. /**
  25423. * Gets the value of a local script variable.
  25424. *
  25425. * @param {string} name - The variable name.
  25426. * @return {Object} The value.
  25427. */
  25428. getLocal( name ) {
  25429. return this._local.get( name );
  25430. }
  25431. /**
  25432. * Event listener for the `refresh` event.
  25433. */
  25434. onRefresh() {
  25435. this._refresh();
  25436. }
  25437. /**
  25438. * Returns an input from the layout with the given id/name.
  25439. *
  25440. * @param {string} id - The id/name of the input.
  25441. * @return {Object} The element entry.
  25442. */
  25443. getInputLayout( id ) {
  25444. for ( const element of this.getLayout() ) {
  25445. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  25446. return element;
  25447. }
  25448. }
  25449. }
  25450. /**
  25451. * Returns an output from the layout with the given id/name.
  25452. *
  25453. * @param {string} id - The id/name of the output.
  25454. * @return {Object} The element entry.
  25455. */
  25456. getOutputLayout( id ) {
  25457. for ( const element of this.getLayout() ) {
  25458. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  25459. return element;
  25460. }
  25461. }
  25462. }
  25463. /**
  25464. * Defines a script output for the given name and value.
  25465. *
  25466. * @param {string} name - The name of the output.
  25467. * @param {Node} value - The node value.
  25468. * @return {ScriptableNode} A reference to this node.
  25469. */
  25470. setOutput( name, value ) {
  25471. const outputs = this._outputs;
  25472. if ( outputs[ name ] === undefined ) {
  25473. outputs[ name ] = scriptableValue( value );
  25474. } else {
  25475. outputs[ name ].value = value;
  25476. }
  25477. return this;
  25478. }
  25479. /**
  25480. * Returns a script output for the given name.
  25481. *
  25482. * @param {string} name - The name of the output.
  25483. * @return {ScriptableValueNode} The node value.
  25484. */
  25485. getOutput( name ) {
  25486. return this._outputs[ name ];
  25487. }
  25488. /**
  25489. * Returns a parameter for the given name
  25490. *
  25491. * @param {string} name - The name of the parameter.
  25492. * @return {ScriptableValueNode} The node value.
  25493. */
  25494. getParameter( name ) {
  25495. return this.parameters[ name ];
  25496. }
  25497. /**
  25498. * Sets a value for the given parameter name.
  25499. *
  25500. * @param {string} name - The parameter name.
  25501. * @param {any} value - The parameter value.
  25502. * @return {ScriptableNode} A reference to this node.
  25503. */
  25504. setParameter( name, value ) {
  25505. const parameters = this.parameters;
  25506. if ( value && value.isScriptableNode ) {
  25507. this.deleteParameter( name );
  25508. parameters[ name ] = value;
  25509. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  25510. } else if ( value && value.isScriptableValueNode ) {
  25511. this.deleteParameter( name );
  25512. parameters[ name ] = value;
  25513. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25514. } else if ( parameters[ name ] === undefined ) {
  25515. parameters[ name ] = scriptableValue( value );
  25516. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25517. } else {
  25518. parameters[ name ].value = value;
  25519. }
  25520. return this;
  25521. }
  25522. /**
  25523. * Returns the value of this node which is the value of
  25524. * the default output.
  25525. *
  25526. * @return {Node} The value.
  25527. */
  25528. getValue() {
  25529. return this.getDefaultOutput().getValue();
  25530. }
  25531. /**
  25532. * Deletes a parameter from the script.
  25533. *
  25534. * @param {string} name - The parameter to remove.
  25535. * @return {ScriptableNode} A reference to this node.
  25536. */
  25537. deleteParameter( name ) {
  25538. let valueNode = this.parameters[ name ];
  25539. if ( valueNode ) {
  25540. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25541. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  25542. }
  25543. return this;
  25544. }
  25545. /**
  25546. * Deletes all parameters from the script.
  25547. *
  25548. * @return {ScriptableNode} A reference to this node.
  25549. */
  25550. clearParameters() {
  25551. for ( const name of Object.keys( this.parameters ) ) {
  25552. this.deleteParameter( name );
  25553. }
  25554. this.needsUpdate = true;
  25555. return this;
  25556. }
  25557. /**
  25558. * Calls a function from the script.
  25559. *
  25560. * @param {string} name - The function name.
  25561. * @param {...any} params - A list of parameters.
  25562. * @return {any} The result of the function call.
  25563. */
  25564. call( name, ...params ) {
  25565. const object = this.getObject();
  25566. const method = object[ name ];
  25567. if ( typeof method === 'function' ) {
  25568. return method( ...params );
  25569. }
  25570. }
  25571. /**
  25572. * Asynchronously calls a function from the script.
  25573. *
  25574. * @param {string} name - The function name.
  25575. * @param {...any} params - A list of parameters.
  25576. * @return {Promise<any>} The result of the function call.
  25577. */
  25578. async callAsync( name, ...params ) {
  25579. const object = this.getObject();
  25580. const method = object[ name ];
  25581. if ( typeof method === 'function' ) {
  25582. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  25583. }
  25584. }
  25585. /**
  25586. * Overwritten since the node types is inferred from the script's output.
  25587. *
  25588. * @param {NodeBuilder} builder - The current node builder
  25589. * @return {string} The node type.
  25590. */
  25591. getNodeType( builder ) {
  25592. return this.getDefaultOutputNode().getNodeType( builder );
  25593. }
  25594. /**
  25595. * Refreshes the script node.
  25596. *
  25597. * @param {?string} [output=null] - An optional output.
  25598. */
  25599. refresh( output = null ) {
  25600. if ( output !== null ) {
  25601. this.getOutput( output ).refresh();
  25602. } else {
  25603. this._refresh();
  25604. }
  25605. }
  25606. /**
  25607. * Returns an object representation of the script.
  25608. *
  25609. * @return {Object} The result object.
  25610. */
  25611. getObject() {
  25612. if ( this.needsUpdate ) this.dispose();
  25613. if ( this._object !== null ) return this._object;
  25614. //
  25615. const refresh = () => this.refresh();
  25616. const setOutput = ( id, value ) => this.setOutput( id, value );
  25617. const parameters = new Parameters( this );
  25618. const THREE = ScriptableNodeResources.get( 'THREE' );
  25619. const TSL = ScriptableNodeResources.get( 'TSL' );
  25620. const method = this.getMethod();
  25621. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  25622. this._object = method( ...params );
  25623. const layout = this._object.layout;
  25624. if ( layout ) {
  25625. if ( layout.cache === false ) {
  25626. this._local.clear();
  25627. }
  25628. // default output
  25629. this._output.outputType = layout.outputType || null;
  25630. if ( Array.isArray( layout.elements ) ) {
  25631. for ( const element of layout.elements ) {
  25632. const id = element.id || element.name;
  25633. if ( element.inputType ) {
  25634. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  25635. this.getParameter( id ).inputType = element.inputType;
  25636. }
  25637. if ( element.outputType ) {
  25638. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  25639. this.getOutput( id ).outputType = element.outputType;
  25640. }
  25641. }
  25642. }
  25643. }
  25644. return this._object;
  25645. }
  25646. deserialize( data ) {
  25647. super.deserialize( data );
  25648. for ( const name in this.parameters ) {
  25649. let valueNode = this.parameters[ name ];
  25650. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25651. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  25652. }
  25653. }
  25654. /**
  25655. * Returns the layout of the script.
  25656. *
  25657. * @return {Object} The script's layout.
  25658. */
  25659. getLayout() {
  25660. return this.getObject().layout;
  25661. }
  25662. /**
  25663. * Returns default node output of the script.
  25664. *
  25665. * @return {Node} The default node output.
  25666. */
  25667. getDefaultOutputNode() {
  25668. const output = this.getDefaultOutput().value;
  25669. if ( output && output.isNode ) {
  25670. return output;
  25671. }
  25672. return float();
  25673. }
  25674. /**
  25675. * Returns default output of the script.
  25676. *
  25677. * @return {ScriptableValueNode} The default output.
  25678. */
  25679. getDefaultOutput() {
  25680. return this._exec()._output;
  25681. }
  25682. /**
  25683. * Returns a function created from the node's script.
  25684. *
  25685. * @return {Function} The function representing the node's code.
  25686. */
  25687. getMethod() {
  25688. if ( this.needsUpdate ) this.dispose();
  25689. if ( this._method !== null ) return this._method;
  25690. //
  25691. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  25692. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  25693. const properties = interfaceProps.join( ', ' );
  25694. const declarations = 'var ' + properties + '; var output = {};\n';
  25695. const returns = '\nreturn { ...output, ' + properties + ' };';
  25696. const code = declarations + this.codeNode.code + returns;
  25697. //
  25698. this._method = new Function( ...parametersProps, code );
  25699. return this._method;
  25700. }
  25701. /**
  25702. * Frees all internal resources.
  25703. */
  25704. dispose() {
  25705. if ( this._method === null ) return;
  25706. if ( this._object && typeof this._object.dispose === 'function' ) {
  25707. this._object.dispose();
  25708. }
  25709. this._method = null;
  25710. this._object = null;
  25711. this._source = null;
  25712. this._value = null;
  25713. this._needsOutputUpdate = true;
  25714. this._output.value = null;
  25715. this._outputs = {};
  25716. }
  25717. setup() {
  25718. return this.getDefaultOutputNode();
  25719. }
  25720. getCacheKey( force ) {
  25721. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  25722. for ( const param in this.parameters ) {
  25723. values.push( this.parameters[ param ].getCacheKey( force ) );
  25724. }
  25725. return hashArray( values );
  25726. }
  25727. set needsUpdate( value ) {
  25728. if ( value === true ) this.dispose();
  25729. }
  25730. get needsUpdate() {
  25731. return this.source !== this._source;
  25732. }
  25733. /**
  25734. * Executes the `main` function of the script.
  25735. *
  25736. * @private
  25737. * @return {ScriptableNode} A reference to this node.
  25738. */
  25739. _exec() {
  25740. if ( this.codeNode === null ) return this;
  25741. if ( this._needsOutputUpdate === true ) {
  25742. this._value = this.call( 'main' );
  25743. this._needsOutputUpdate = false;
  25744. }
  25745. this._output.value = this._value;
  25746. return this;
  25747. }
  25748. /**
  25749. * Executes the refresh.
  25750. *
  25751. * @private
  25752. */
  25753. _refresh() {
  25754. this.needsUpdate = true;
  25755. this._exec();
  25756. this._output.refresh();
  25757. }
  25758. }
  25759. /**
  25760. * TSL function for creating a scriptable node.
  25761. *
  25762. * @tsl
  25763. * @function
  25764. * @param {CodeNode} [codeNode] - The code node.
  25765. * @param {?Object} [parameters={}] - The parameters definition.
  25766. * @returns {ScriptableNode}
  25767. */
  25768. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  25769. /**
  25770. * Returns a node that represents the `z` coordinate in view space
  25771. * for the current fragment. It's a different representation of the
  25772. * default depth value.
  25773. *
  25774. * This value can be part of a computation that defines how the fog
  25775. * density increases when moving away from the camera.
  25776. *
  25777. * @param {NodeBuilder} builder - The current node builder.
  25778. * @return {Node} The viewZ node.
  25779. */
  25780. function getViewZNode( builder ) {
  25781. let viewZ;
  25782. const getViewZ = builder.context.getViewZ;
  25783. if ( getViewZ !== undefined ) {
  25784. viewZ = getViewZ( this );
  25785. }
  25786. return ( viewZ || positionView.z ).negate();
  25787. }
  25788. /**
  25789. * Constructs a new range factor node.
  25790. *
  25791. * @tsl
  25792. * @function
  25793. * @param {Node} near - Defines the near value.
  25794. * @param {Node} far - Defines the far value.
  25795. */
  25796. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  25797. const viewZ = getViewZNode( builder );
  25798. return smoothstep( near, far, viewZ );
  25799. } );
  25800. /**
  25801. * Represents an exponential squared fog. This type of fog gives
  25802. * a clear view near the camera and a faster than exponentially
  25803. * densening fog farther from the camera.
  25804. *
  25805. * @tsl
  25806. * @function
  25807. * @param {Node} density - Defines the fog density.
  25808. */
  25809. const densityFogFactor = Fn( ( [ density ], builder ) => {
  25810. const viewZ = getViewZNode( builder );
  25811. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  25812. } );
  25813. /**
  25814. * This class can be used to configure a fog for the scene.
  25815. * Nodes of this type are assigned to `Scene.fogNode`.
  25816. *
  25817. * @tsl
  25818. * @function
  25819. * @param {Node} color - Defines the color of the fog.
  25820. * @param {Node} factor - Defines how the fog is factored in the scene.
  25821. */
  25822. const fog = Fn( ( [ color, factor ] ) => {
  25823. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  25824. } );
  25825. // Deprecated
  25826. /**
  25827. * @tsl
  25828. * @function
  25829. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  25830. *
  25831. * @param {Node} color
  25832. * @param {Node} near
  25833. * @param {Node} far
  25834. * @returns {Function}
  25835. */
  25836. function rangeFog( color, near, far ) { // @deprecated, r171
  25837. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  25838. return fog( color, rangeFogFactor( near, far ) );
  25839. }
  25840. /**
  25841. * @tsl
  25842. * @function
  25843. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  25844. *
  25845. * @param {Node} color
  25846. * @param {Node} density
  25847. * @returns {Function}
  25848. */
  25849. function densityFog( color, density ) { // @deprecated, r171
  25850. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  25851. return fog( color, densityFogFactor( density ) );
  25852. }
  25853. let min = null;
  25854. let max = null;
  25855. /**
  25856. * `RangeNode` generates random instanced attribute data in a defined range.
  25857. * An exemplary use case for this utility node is to generate random per-instance
  25858. * colors:
  25859. * ```js
  25860. * const material = new MeshBasicNodeMaterial();
  25861. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  25862. * const mesh = new InstancedMesh( geometry, material, count );
  25863. * ```
  25864. * @augments Node
  25865. */
  25866. class RangeNode extends Node {
  25867. static get type() {
  25868. return 'RangeNode';
  25869. }
  25870. /**
  25871. * Constructs a new range node.
  25872. *
  25873. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  25874. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  25875. */
  25876. constructor( minNode = float(), maxNode = float() ) {
  25877. super();
  25878. /**
  25879. * A node defining the lower bound of the range.
  25880. *
  25881. * @type {Node<any>}
  25882. * @default float()
  25883. */
  25884. this.minNode = minNode;
  25885. /**
  25886. * A node defining the upper bound of the range.
  25887. *
  25888. * @type {Node<any>}
  25889. * @default float()
  25890. */
  25891. this.maxNode = maxNode;
  25892. }
  25893. /**
  25894. * Returns the vector length which is computed based on the range definition.
  25895. *
  25896. * @param {NodeBuilder} builder - The current node builder.
  25897. * @return {number} The vector length.
  25898. */
  25899. getVectorLength( builder ) {
  25900. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  25901. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  25902. return minLength > maxLength ? minLength : maxLength;
  25903. }
  25904. /**
  25905. * This method is overwritten since the node type is inferred from range definition.
  25906. *
  25907. * @param {NodeBuilder} builder - The current node builder.
  25908. * @return {string} The node type.
  25909. */
  25910. getNodeType( builder ) {
  25911. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  25912. }
  25913. setup( builder ) {
  25914. const object = builder.object;
  25915. let output = null;
  25916. if ( object.count > 1 ) {
  25917. const minValue = this.minNode.value;
  25918. const maxValue = this.maxNode.value;
  25919. const minLength = builder.getTypeLength( getValueType( minValue ) );
  25920. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  25921. min = min || new Vector4();
  25922. max = max || new Vector4();
  25923. min.setScalar( 0 );
  25924. max.setScalar( 0 );
  25925. if ( minLength === 1 ) min.setScalar( minValue );
  25926. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  25927. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  25928. if ( maxLength === 1 ) max.setScalar( maxValue );
  25929. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  25930. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  25931. const stride = 4;
  25932. const length = stride * object.count;
  25933. const array = new Float32Array( length );
  25934. for ( let i = 0; i < length; i ++ ) {
  25935. const index = i % stride;
  25936. const minElementValue = min.getComponent( index );
  25937. const maxElementValue = max.getComponent( index );
  25938. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  25939. }
  25940. const nodeType = this.getNodeType( builder );
  25941. if ( object.count <= 4096 ) {
  25942. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  25943. } else {
  25944. // TODO: Improve anonymous buffer attribute creation removing this part
  25945. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  25946. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  25947. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  25948. }
  25949. } else {
  25950. output = float( 0 );
  25951. }
  25952. return output;
  25953. }
  25954. }
  25955. /**
  25956. * TSL function for creating a range node.
  25957. *
  25958. * @tsl
  25959. * @function
  25960. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  25961. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  25962. * @returns {RangeNode}
  25963. */
  25964. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  25965. /**
  25966. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  25967. * about the currently running dispatch and/or the device it is running on.
  25968. *
  25969. * This node can only be used with a WebGPU backend.
  25970. *
  25971. * @augments Node
  25972. */
  25973. class ComputeBuiltinNode extends Node {
  25974. static get type() {
  25975. return 'ComputeBuiltinNode';
  25976. }
  25977. /**
  25978. * Constructs a new compute builtin node.
  25979. *
  25980. * @param {string} builtinName - The built-in name.
  25981. * @param {string} nodeType - The node type.
  25982. */
  25983. constructor( builtinName, nodeType ) {
  25984. super( nodeType );
  25985. /**
  25986. * The built-in name.
  25987. *
  25988. * @private
  25989. * @type {string}
  25990. */
  25991. this._builtinName = builtinName;
  25992. }
  25993. /**
  25994. * This method is overwritten since hash is derived from the built-in name.
  25995. *
  25996. * @param {NodeBuilder} builder - The current node builder.
  25997. * @return {string} The hash.
  25998. */
  25999. getHash( builder ) {
  26000. return this.getBuiltinName( builder );
  26001. }
  26002. /**
  26003. * This method is overwritten since the node type is simply derived from `nodeType`..
  26004. *
  26005. * @param {NodeBuilder} builder - The current node builder.
  26006. * @return {string} The node type.
  26007. */
  26008. getNodeType( /*builder*/ ) {
  26009. return this.nodeType;
  26010. }
  26011. /**
  26012. * Sets the builtin name.
  26013. *
  26014. * @param {string} builtinName - The built-in name.
  26015. * @return {ComputeBuiltinNode} A reference to this node.
  26016. */
  26017. setBuiltinName( builtinName ) {
  26018. this._builtinName = builtinName;
  26019. return this;
  26020. }
  26021. /**
  26022. * Returns the builtin name.
  26023. *
  26024. * @param {NodeBuilder} builder - The current node builder.
  26025. * @return {string} The builtin name.
  26026. */
  26027. getBuiltinName( /*builder*/ ) {
  26028. return this._builtinName;
  26029. }
  26030. /**
  26031. * Whether the current node builder has the builtin or not.
  26032. *
  26033. * @param {NodeBuilder} builder - The current node builder.
  26034. * @return {boolean} Whether the builder has the builtin or not.
  26035. */
  26036. hasBuiltin( builder ) {
  26037. return builder.hasBuiltin( this._builtinName );
  26038. }
  26039. generate( builder, output ) {
  26040. const builtinName = this.getBuiltinName( builder );
  26041. const nodeType = this.getNodeType( builder );
  26042. if ( builder.shaderStage === 'compute' ) {
  26043. return builder.format( builtinName, nodeType, output );
  26044. } else {
  26045. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  26046. return builder.generateConst( nodeType );
  26047. }
  26048. }
  26049. serialize( data ) {
  26050. super.serialize( data );
  26051. data.global = this.global;
  26052. data._builtinName = this._builtinName;
  26053. }
  26054. deserialize( data ) {
  26055. super.deserialize( data );
  26056. this.global = data.global;
  26057. this._builtinName = data._builtinName;
  26058. }
  26059. }
  26060. /**
  26061. * TSL function for creating a compute builtin node.
  26062. *
  26063. * @tsl
  26064. * @function
  26065. * @param {string} name - The built-in name.
  26066. * @param {string} nodeType - The node type.
  26067. * @returns {ComputeBuiltinNode}
  26068. */
  26069. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  26070. /**
  26071. * Represents the number of workgroups dispatched by the compute shader.
  26072. * ```js
  26073. * // Run 512 invocations/threads with a workgroup size of 128.
  26074. * const computeFn = Fn(() => {
  26075. *
  26076. * // numWorkgroups.x = 4
  26077. * storageBuffer.element(0).assign(numWorkgroups.x)
  26078. *
  26079. * })().compute(512, [128]);
  26080. *
  26081. * // Run 512 invocations/threads with the default workgroup size of 64.
  26082. * const computeFn = Fn(() => {
  26083. *
  26084. * // numWorkgroups.x = 8
  26085. * storageBuffer.element(0).assign(numWorkgroups.x)
  26086. *
  26087. * })().compute(512);
  26088. * ```
  26089. *
  26090. * @tsl
  26091. * @type {ComputeBuiltinNode<uvec3>}
  26092. */
  26093. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  26094. /**
  26095. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  26096. * ```js
  26097. * // Execute 12 compute threads with a workgroup size of 3.
  26098. * const computeFn = Fn( () => {
  26099. *
  26100. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  26101. *
  26102. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  26103. *
  26104. * } ).Else( () => {
  26105. *
  26106. * storageBuffer.element( instanceIndex ).assign( 0 );
  26107. *
  26108. * } );
  26109. *
  26110. * } )().compute( 12, [ 3 ] );
  26111. *
  26112. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  26113. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  26114. * ```
  26115. *
  26116. * @tsl
  26117. * @type {ComputeBuiltinNode<uvec3>}
  26118. */
  26119. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  26120. /**
  26121. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  26122. *
  26123. * @tsl
  26124. * @type {ComputeBuiltinNode<uvec3>}
  26125. */
  26126. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  26127. /**
  26128. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  26129. *
  26130. * @tsl
  26131. * @type {ComputeBuiltinNode<uvec3>}
  26132. */
  26133. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  26134. /**
  26135. * A device dependent variable that exposes the size of the current invocation's subgroup.
  26136. *
  26137. * @tsl
  26138. * @type {ComputeBuiltinNode<uint>}
  26139. */
  26140. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  26141. /**
  26142. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  26143. *
  26144. * This node can only be used with a WebGPU backend.
  26145. *
  26146. * @augments Node
  26147. */
  26148. class BarrierNode extends Node {
  26149. /**
  26150. * Constructs a new barrier node.
  26151. *
  26152. * @param {string} scope - The scope defines the behavior of the node.
  26153. */
  26154. constructor( scope ) {
  26155. super();
  26156. this.scope = scope;
  26157. }
  26158. generate( builder ) {
  26159. const { scope } = this;
  26160. const { renderer } = builder;
  26161. if ( renderer.backend.isWebGLBackend === true ) {
  26162. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  26163. } else {
  26164. builder.addLineFlowCode( `${scope}Barrier()`, this );
  26165. }
  26166. }
  26167. }
  26168. /**
  26169. * TSL function for creating a barrier node.
  26170. *
  26171. * @tsl
  26172. * @function
  26173. * @param {string} scope - The scope defines the behavior of the node..
  26174. * @returns {BarrierNode}
  26175. */
  26176. const barrier = nodeProxy( BarrierNode );
  26177. /**
  26178. * TSL function for creating a workgroup barrier. All compute shader
  26179. * invocations must wait for each invocation within a workgroup to
  26180. * complete before the barrier can be surpassed.
  26181. *
  26182. * @tsl
  26183. * @function
  26184. * @returns {BarrierNode}
  26185. */
  26186. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  26187. /**
  26188. * TSL function for creating a storage barrier. All invocations must
  26189. * wait for each access to variables within the 'storage' address space
  26190. * to complete before the barrier can be passed.
  26191. *
  26192. * @tsl
  26193. * @function
  26194. * @returns {BarrierNode}
  26195. */
  26196. const storageBarrier = () => barrier( 'storage' ).toStack();
  26197. /**
  26198. * TSL function for creating a texture barrier. All invocations must
  26199. * wait for each access to variables within the 'texture' address space
  26200. * to complete before the barrier can be passed.
  26201. *
  26202. * @tsl
  26203. * @function
  26204. * @returns {BarrierNode}
  26205. */
  26206. const textureBarrier = () => barrier( 'texture' ).toStack();
  26207. /**
  26208. * Represents an element of a 'workgroup' scoped buffer.
  26209. *
  26210. * @augments ArrayElementNode
  26211. */
  26212. class WorkgroupInfoElementNode extends ArrayElementNode {
  26213. /**
  26214. * Constructs a new workgroup info element node.
  26215. *
  26216. * @param {Node} workgroupInfoNode - The workgroup info node.
  26217. * @param {Node} indexNode - The index node that defines the element access.
  26218. */
  26219. constructor( workgroupInfoNode, indexNode ) {
  26220. super( workgroupInfoNode, indexNode );
  26221. /**
  26222. * This flag can be used for type testing.
  26223. *
  26224. * @type {boolean}
  26225. * @readonly
  26226. * @default true
  26227. */
  26228. this.isWorkgroupInfoElementNode = true;
  26229. }
  26230. generate( builder, output ) {
  26231. let snippet;
  26232. const isAssignContext = builder.context.assign;
  26233. snippet = super.generate( builder );
  26234. if ( isAssignContext !== true ) {
  26235. const type = this.getNodeType( builder );
  26236. snippet = builder.format( snippet, type, output );
  26237. }
  26238. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  26239. return snippet;
  26240. }
  26241. }
  26242. /**
  26243. * A node allowing the user to create a 'workgroup' scoped buffer within the
  26244. * context of a compute shader. Typically, workgroup scoped buffers are
  26245. * created to hold data that is transferred from a global storage scope into
  26246. * a local workgroup scope. For invocations within a workgroup, data
  26247. * access speeds on 'workgroup' scoped buffers can be significantly faster
  26248. * than similar access operations on globally accessible storage buffers.
  26249. *
  26250. * This node can only be used with a WebGPU backend.
  26251. *
  26252. * @augments Node
  26253. */
  26254. class WorkgroupInfoNode extends Node {
  26255. /**
  26256. * Constructs a new buffer scoped to type scope.
  26257. *
  26258. * @param {string} scope - TODO.
  26259. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  26260. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  26261. */
  26262. constructor( scope, bufferType, bufferCount = 0 ) {
  26263. super( bufferType );
  26264. /**
  26265. * The buffer type.
  26266. *
  26267. * @type {string}
  26268. */
  26269. this.bufferType = bufferType;
  26270. /**
  26271. * The buffer count.
  26272. *
  26273. * @type {number}
  26274. * @default 0
  26275. */
  26276. this.bufferCount = bufferCount;
  26277. /**
  26278. * This flag can be used for type testing.
  26279. *
  26280. * @type {boolean}
  26281. * @readonly
  26282. * @default true
  26283. */
  26284. this.isWorkgroupInfoNode = true;
  26285. /**
  26286. * The data type of the array buffer.
  26287. *
  26288. * @type {string}
  26289. */
  26290. this.elementType = bufferType;
  26291. /**
  26292. * TODO.
  26293. *
  26294. * @type {string}
  26295. */
  26296. this.scope = scope;
  26297. }
  26298. /**
  26299. * Sets the name/label of this node.
  26300. *
  26301. * @param {string} name - The name to set.
  26302. * @return {WorkgroupInfoNode} A reference to this node.
  26303. */
  26304. label( name ) {
  26305. this.name = name;
  26306. return this;
  26307. }
  26308. /**
  26309. * Sets the scope of this node.
  26310. *
  26311. * @param {string} scope - The scope to set.
  26312. * @return {WorkgroupInfoNode} A reference to this node.
  26313. */
  26314. setScope( scope ) {
  26315. this.scope = scope;
  26316. return this;
  26317. }
  26318. /**
  26319. * The data type of the array buffer.
  26320. *
  26321. * @return {string} The element type.
  26322. */
  26323. getElementType() {
  26324. return this.elementType;
  26325. }
  26326. /**
  26327. * Overwrites the default implementation since the input type
  26328. * is inferred from the scope.
  26329. *
  26330. * @param {NodeBuilder} builder - The current node builder.
  26331. * @return {string} The input type.
  26332. */
  26333. getInputType( /*builder*/ ) {
  26334. return `${this.scope}Array`;
  26335. }
  26336. /**
  26337. * This method can be used to access elements via an index node.
  26338. *
  26339. * @param {IndexNode} indexNode - indexNode.
  26340. * @return {WorkgroupInfoElementNode} A reference to an element.
  26341. */
  26342. element( indexNode ) {
  26343. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  26344. }
  26345. generate( builder ) {
  26346. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  26347. }
  26348. }
  26349. /**
  26350. * TSL function for creating a workgroup info node.
  26351. * Creates a new 'workgroup' scoped array buffer.
  26352. *
  26353. * @tsl
  26354. * @function
  26355. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  26356. * @param {number} [count=0] - The number of elements in the buffer.
  26357. * @returns {WorkgroupInfoNode}
  26358. */
  26359. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  26360. /**
  26361. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  26362. * within a shader. In an atomic function, any modification to an atomic variable will
  26363. * occur as an indivisible step with a defined order relative to other modifications.
  26364. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  26365. * atomic operations will not interfere with each other.
  26366. *
  26367. * This node can only be used with a WebGPU backend.
  26368. *
  26369. * @augments Node
  26370. */
  26371. class AtomicFunctionNode extends Node {
  26372. static get type() {
  26373. return 'AtomicFunctionNode';
  26374. }
  26375. /**
  26376. * Constructs a new atomic function node.
  26377. *
  26378. * @param {string} method - The signature of the atomic function to construct.
  26379. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26380. * @param {Node} valueNode - The value that mutates the atomic variable.
  26381. */
  26382. constructor( method, pointerNode, valueNode ) {
  26383. super( 'uint' );
  26384. /**
  26385. * The signature of the atomic function to construct.
  26386. *
  26387. * @type {string}
  26388. */
  26389. this.method = method;
  26390. /**
  26391. * An atomic variable or element of an atomic buffer.
  26392. *
  26393. * @type {Node}
  26394. */
  26395. this.pointerNode = pointerNode;
  26396. /**
  26397. * A value that modifies the atomic variable.
  26398. *
  26399. * @type {Node}
  26400. */
  26401. this.valueNode = valueNode;
  26402. /**
  26403. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  26404. *
  26405. * @type {boolean}
  26406. * @default true
  26407. */
  26408. this.parents = true;
  26409. }
  26410. /**
  26411. * Overwrites the default implementation to return the type of
  26412. * the pointer node.
  26413. *
  26414. * @param {NodeBuilder} builder - The current node builder.
  26415. * @return {string} The input type.
  26416. */
  26417. getInputType( builder ) {
  26418. return this.pointerNode.getNodeType( builder );
  26419. }
  26420. /**
  26421. * Overwritten since the node type is inferred from the input type.
  26422. *
  26423. * @param {NodeBuilder} builder - The current node builder.
  26424. * @return {string} The node type.
  26425. */
  26426. getNodeType( builder ) {
  26427. return this.getInputType( builder );
  26428. }
  26429. generate( builder ) {
  26430. const properties = builder.getNodeProperties( this );
  26431. const parents = properties.parents;
  26432. const method = this.method;
  26433. const type = this.getNodeType( builder );
  26434. const inputType = this.getInputType( builder );
  26435. const a = this.pointerNode;
  26436. const b = this.valueNode;
  26437. const params = [];
  26438. params.push( `&${ a.build( builder, inputType ) }` );
  26439. if ( b !== null ) {
  26440. params.push( b.build( builder, inputType ) );
  26441. }
  26442. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  26443. const isVoid = parents.length === 1 && parents[ 0 ].isStackNode === true;
  26444. if ( isVoid ) {
  26445. builder.addLineFlowCode( methodSnippet, this );
  26446. } else {
  26447. if ( properties.constNode === undefined ) {
  26448. properties.constNode = expression( methodSnippet, type ).toConst();
  26449. }
  26450. return properties.constNode.build( builder );
  26451. }
  26452. }
  26453. }
  26454. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  26455. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  26456. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  26457. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  26458. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  26459. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  26460. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  26461. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  26462. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  26463. /**
  26464. * TSL function for creating an atomic function node.
  26465. *
  26466. * @tsl
  26467. * @function
  26468. * @param {string} method - The signature of the atomic function to construct.
  26469. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26470. * @param {Node} valueNode - The value that mutates the atomic variable.
  26471. * @returns {AtomicFunctionNode}
  26472. */
  26473. const atomicNode = nodeProxy( AtomicFunctionNode );
  26474. /**
  26475. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  26476. *
  26477. * @tsl
  26478. * @function
  26479. * @param {string} method - The signature of the atomic function to construct.
  26480. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26481. * @param {Node} valueNode - The value that mutates the atomic variable.
  26482. * @returns {AtomicFunctionNode}
  26483. */
  26484. const atomicFunc = ( method, pointerNode, valueNode ) => {
  26485. return atomicNode( method, pointerNode, valueNode ).toStack();
  26486. };
  26487. /**
  26488. * Loads the value stored in the atomic variable.
  26489. *
  26490. * @tsl
  26491. * @function
  26492. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26493. * @returns {AtomicFunctionNode}
  26494. */
  26495. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  26496. /**
  26497. * Stores a value in the atomic variable.
  26498. *
  26499. * @tsl
  26500. * @function
  26501. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26502. * @param {Node} valueNode - The value that mutates the atomic variable.
  26503. * @returns {AtomicFunctionNode}
  26504. */
  26505. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  26506. /**
  26507. * Increments the value stored in the atomic variable.
  26508. *
  26509. * @tsl
  26510. * @function
  26511. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26512. * @param {Node} valueNode - The value that mutates the atomic variable.
  26513. * @returns {AtomicFunctionNode}
  26514. */
  26515. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  26516. /**
  26517. * Decrements the value stored in the atomic variable.
  26518. *
  26519. * @tsl
  26520. * @function
  26521. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26522. * @param {Node} valueNode - The value that mutates the atomic variable.
  26523. * @returns {AtomicFunctionNode}
  26524. */
  26525. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  26526. /**
  26527. * Stores in an atomic variable the maximum between its current value and a parameter.
  26528. *
  26529. * @tsl
  26530. * @function
  26531. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26532. * @param {Node} valueNode - The value that mutates the atomic variable.
  26533. * @returns {AtomicFunctionNode}
  26534. */
  26535. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  26536. /**
  26537. * Stores in an atomic variable the minimum between its current value and a parameter.
  26538. *
  26539. * @tsl
  26540. * @function
  26541. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26542. * @param {Node} valueNode - The value that mutates the atomic variable.
  26543. * @returns {AtomicFunctionNode}
  26544. */
  26545. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  26546. /**
  26547. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  26548. *
  26549. * @tsl
  26550. * @function
  26551. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26552. * @param {Node} valueNode - The value that mutates the atomic variable.
  26553. * @returns {AtomicFunctionNode}
  26554. */
  26555. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  26556. /**
  26557. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  26558. *
  26559. * @tsl
  26560. * @function
  26561. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26562. * @param {Node} valueNode - The value that mutates the atomic variable.
  26563. * @returns {AtomicFunctionNode}
  26564. */
  26565. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  26566. /**
  26567. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  26568. *
  26569. * @tsl
  26570. * @function
  26571. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26572. * @param {Node} valueNode - The value that mutates the atomic variable.
  26573. * @returns {AtomicFunctionNode}
  26574. */
  26575. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  26576. let uniformsLib;
  26577. function getLightData( light ) {
  26578. uniformsLib = uniformsLib || new WeakMap();
  26579. let uniforms = uniformsLib.get( light );
  26580. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  26581. return uniforms;
  26582. }
  26583. /**
  26584. * TSL function for getting a shadow matrix uniform node for the given light.
  26585. *
  26586. * @tsl
  26587. * @function
  26588. * @param {Light} light -The light source.
  26589. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  26590. */
  26591. function lightShadowMatrix( light ) {
  26592. const data = getLightData( light );
  26593. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  26594. if ( light.castShadow !== true ) {
  26595. light.shadow.updateMatrices( light );
  26596. }
  26597. return light.shadow.matrix;
  26598. } ) );
  26599. }
  26600. /**
  26601. * TSL function for getting projected uv coordinates for the given light.
  26602. * Relevant when using maps with spot lights.
  26603. *
  26604. * @tsl
  26605. * @function
  26606. * @param {Light} light -The light source.
  26607. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  26608. * @returns {Node<vec3>} The projected uvs.
  26609. */
  26610. function lightProjectionUV( light, position = positionWorld ) {
  26611. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  26612. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  26613. return projectionUV;
  26614. }
  26615. /**
  26616. * TSL function for getting the position in world space for the given light.
  26617. *
  26618. * @tsl
  26619. * @function
  26620. * @param {Light} light -The light source.
  26621. * @returns {UniformNode<vec3>} The light's position in world space.
  26622. */
  26623. function lightPosition( light ) {
  26624. const data = getLightData( light );
  26625. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  26626. }
  26627. /**
  26628. * TSL function for getting the light target position in world space for the given light.
  26629. *
  26630. * @tsl
  26631. * @function
  26632. * @param {Light} light -The light source.
  26633. * @returns {UniformNode<vec3>} The light target position in world space.
  26634. */
  26635. function lightTargetPosition( light ) {
  26636. const data = getLightData( light );
  26637. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  26638. }
  26639. /**
  26640. * TSL function for getting the position in view space for the given light.
  26641. *
  26642. * @tsl
  26643. * @function
  26644. * @param {Light} light - The light source.
  26645. * @returns {UniformNode<vec3>} The light's position in view space.
  26646. */
  26647. function lightViewPosition( light ) {
  26648. const data = getLightData( light );
  26649. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  26650. self.value = self.value || new Vector3();
  26651. self.value.setFromMatrixPosition( light.matrixWorld );
  26652. self.value.applyMatrix4( camera.matrixWorldInverse );
  26653. } ) );
  26654. }
  26655. /**
  26656. * TSL function for getting the light target direction for the given light.
  26657. *
  26658. * @tsl
  26659. * @function
  26660. * @param {Light} light -The light source.
  26661. * @returns {Node<vec3>} The light's target direction.
  26662. */
  26663. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  26664. const sortLights = ( lights ) => {
  26665. return lights.sort( ( a, b ) => a.id - b.id );
  26666. };
  26667. const getLightNodeById = ( id, lightNodes ) => {
  26668. for ( const lightNode of lightNodes ) {
  26669. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  26670. return lightNode;
  26671. }
  26672. }
  26673. return null;
  26674. };
  26675. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  26676. /**
  26677. * This node represents the scene's lighting and manages the lighting model's life cycle
  26678. * for the current build 3D object. It is responsible for computing the total outgoing
  26679. * light in a given lighting context.
  26680. *
  26681. * @augments Node
  26682. */
  26683. class LightsNode extends Node {
  26684. static get type() {
  26685. return 'LightsNode';
  26686. }
  26687. /**
  26688. * Constructs a new lights node.
  26689. */
  26690. constructor() {
  26691. super( 'vec3' );
  26692. /**
  26693. * A node representing the total diffuse light.
  26694. *
  26695. * @type {Node<vec3>}
  26696. */
  26697. this.totalDiffuseNode = vec3().toVar();
  26698. /**
  26699. * A node representing the total specular light.
  26700. *
  26701. * @type {Node<vec3>}
  26702. */
  26703. this.totalSpecularNode = vec3().toVar();
  26704. /**
  26705. * A node representing the outgoing light.
  26706. *
  26707. * @type {Node<vec3>}
  26708. */
  26709. this.outgoingLightNode = vec3().toVar();
  26710. /**
  26711. * An array representing the lights in the scene.
  26712. *
  26713. * @private
  26714. * @type {Array<Light>}
  26715. */
  26716. this._lights = [];
  26717. /**
  26718. * For each light in the scene, this node will create a
  26719. * corresponding light node.
  26720. *
  26721. * @private
  26722. * @type {?Array<LightingNode>}
  26723. * @default null
  26724. */
  26725. this._lightNodes = null;
  26726. /**
  26727. * A hash for identifying the current light nodes setup.
  26728. *
  26729. * @private
  26730. * @type {?string}
  26731. * @default null
  26732. */
  26733. this._lightNodesHash = null;
  26734. /**
  26735. * `LightsNode` sets this property to `true` by default.
  26736. *
  26737. * @type {boolean}
  26738. * @default true
  26739. */
  26740. this.global = true;
  26741. }
  26742. /**
  26743. * Overwrites the default {@link Node#customCacheKey} implementation by including
  26744. * light data into the cache key.
  26745. *
  26746. * @return {number} The custom cache key.
  26747. */
  26748. customCacheKey() {
  26749. const hashData = [];
  26750. const lights = this._lights;
  26751. for ( let i = 0; i < lights.length; i ++ ) {
  26752. const light = lights[ i ];
  26753. hashData.push( light.id );
  26754. if ( light.isSpotLight === true ) {
  26755. const hashValue = ( light.map !== null ) ? light.map.id : -1;
  26756. hashData.push( hashValue );
  26757. }
  26758. }
  26759. return hashArray( hashData );
  26760. }
  26761. /**
  26762. * Computes a hash value for identifying the current light nodes setup.
  26763. *
  26764. * @param {NodeBuilder} builder - A reference to the current node builder.
  26765. * @return {string} The computed hash.
  26766. */
  26767. getHash( builder ) {
  26768. if ( this._lightNodesHash === null ) {
  26769. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26770. const hash = [];
  26771. for ( const lightNode of this._lightNodes ) {
  26772. hash.push( lightNode.getSelf().getHash() );
  26773. }
  26774. this._lightNodesHash = 'lights-' + hash.join( ',' );
  26775. }
  26776. return this._lightNodesHash;
  26777. }
  26778. analyze( builder ) {
  26779. const properties = builder.getDataFromNode( this );
  26780. for ( const node of properties.nodes ) {
  26781. node.build( builder );
  26782. }
  26783. }
  26784. /**
  26785. * Creates lighting nodes for each scene light. This makes it possible to further
  26786. * process lights in the node system.
  26787. *
  26788. * @param {NodeBuilder} builder - A reference to the current node builder.
  26789. */
  26790. setupLightsNode( builder ) {
  26791. const lightNodes = [];
  26792. const previousLightNodes = this._lightNodes;
  26793. const lights = sortLights( this._lights );
  26794. const nodeLibrary = builder.renderer.library;
  26795. for ( const light of lights ) {
  26796. if ( light.isNode ) {
  26797. lightNodes.push( nodeObject( light ) );
  26798. } else {
  26799. let lightNode = null;
  26800. if ( previousLightNodes !== null ) {
  26801. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  26802. }
  26803. if ( lightNode === null ) {
  26804. // find the corresponding node type for a given light
  26805. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  26806. if ( lightNodeClass === null ) {
  26807. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  26808. continue;
  26809. }
  26810. let lightNode = null;
  26811. if ( ! _lightsNodeRef.has( light ) ) {
  26812. lightNode = nodeObject( new lightNodeClass( light ) );
  26813. _lightsNodeRef.set( light, lightNode );
  26814. } else {
  26815. lightNode = _lightsNodeRef.get( light );
  26816. }
  26817. lightNodes.push( lightNode );
  26818. }
  26819. }
  26820. }
  26821. this._lightNodes = lightNodes;
  26822. }
  26823. /**
  26824. * Sets up a direct light in the lighting model.
  26825. *
  26826. * @param {Object} builder - The builder object containing the context and stack.
  26827. * @param {Object} lightNode - The light node.
  26828. * @param {Object} lightData - The light object containing color and direction properties.
  26829. */
  26830. setupDirectLight( builder, lightNode, lightData ) {
  26831. const { lightingModel, reflectedLight } = builder.context;
  26832. lightingModel.direct( {
  26833. ...lightData,
  26834. lightNode,
  26835. reflectedLight
  26836. }, builder );
  26837. }
  26838. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  26839. const { lightingModel, reflectedLight } = builder.context;
  26840. lightingModel.directRectArea( {
  26841. ...lightData,
  26842. lightNode,
  26843. reflectedLight
  26844. }, builder );
  26845. }
  26846. /**
  26847. * Setups the internal lights by building all respective
  26848. * light nodes.
  26849. *
  26850. * @param {NodeBuilder} builder - A reference to the current node builder.
  26851. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  26852. */
  26853. setupLights( builder, lightNodes ) {
  26854. for ( const lightNode of lightNodes ) {
  26855. lightNode.build( builder );
  26856. }
  26857. }
  26858. getLightNodes( builder ) {
  26859. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  26860. return this._lightNodes;
  26861. }
  26862. /**
  26863. * The implementation makes sure that for each light in the scene
  26864. * there is a corresponding light node. By building the light nodes
  26865. * and evaluating the lighting model the outgoing light is computed.
  26866. *
  26867. * @param {NodeBuilder} builder - A reference to the current node builder.
  26868. * @return {Node<vec3>} A node representing the outgoing light.
  26869. */
  26870. setup( builder ) {
  26871. const currentLightsNode = builder.lightsNode;
  26872. builder.lightsNode = this;
  26873. //
  26874. let outgoingLightNode = this.outgoingLightNode;
  26875. const context = builder.context;
  26876. const lightingModel = context.lightingModel;
  26877. const properties = builder.getDataFromNode( this );
  26878. if ( lightingModel ) {
  26879. const { totalDiffuseNode, totalSpecularNode } = this;
  26880. context.outgoingLight = outgoingLightNode;
  26881. const stack = builder.addStack();
  26882. //
  26883. properties.nodes = stack.nodes;
  26884. //
  26885. lightingModel.start( builder );
  26886. //
  26887. const { backdrop, backdropAlpha } = context;
  26888. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  26889. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  26890. if ( backdrop !== null ) {
  26891. if ( backdropAlpha !== null ) {
  26892. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  26893. } else {
  26894. totalDiffuse = vec3( backdrop );
  26895. }
  26896. context.material.transparent = true;
  26897. }
  26898. totalDiffuseNode.assign( totalDiffuse );
  26899. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  26900. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  26901. //
  26902. lightingModel.finish( builder );
  26903. //
  26904. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  26905. } else {
  26906. properties.nodes = [];
  26907. }
  26908. //
  26909. builder.lightsNode = currentLightsNode;
  26910. return outgoingLightNode;
  26911. }
  26912. /**
  26913. * Configures this node with an array of lights.
  26914. *
  26915. * @param {Array<Light>} lights - An array of lights.
  26916. * @return {LightsNode} A reference to this node.
  26917. */
  26918. setLights( lights ) {
  26919. this._lights = lights;
  26920. this._lightNodes = null;
  26921. this._lightNodesHash = null;
  26922. return this;
  26923. }
  26924. /**
  26925. * Returns an array of the scene's lights.
  26926. *
  26927. * @return {Array<Light>} The scene's lights.
  26928. */
  26929. getLights() {
  26930. return this._lights;
  26931. }
  26932. /**
  26933. * Whether the scene has lights or not.
  26934. *
  26935. * @type {boolean}
  26936. */
  26937. get hasLights() {
  26938. return this._lights.length > 0;
  26939. }
  26940. }
  26941. /**
  26942. * TSL function for creating an instance of `LightsNode` and configuring
  26943. * it with the given array of lights.
  26944. *
  26945. * @tsl
  26946. * @function
  26947. * @param {Array<Light>} lights - An array of lights.
  26948. * @return {LightsNode} The created lights node.
  26949. */
  26950. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  26951. /**
  26952. * Base class for all shadow nodes.
  26953. *
  26954. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  26955. * Lighting nodes might share the same shadow node type or use specific ones depending on
  26956. * their requirements.
  26957. *
  26958. * @augments Node
  26959. */
  26960. class ShadowBaseNode extends Node {
  26961. static get type() {
  26962. return 'ShadowBaseNode';
  26963. }
  26964. /**
  26965. * Constructs a new shadow base node.
  26966. *
  26967. * @param {Light} light - The shadow casting light.
  26968. */
  26969. constructor( light ) {
  26970. super();
  26971. /**
  26972. * The shadow casting light.
  26973. *
  26974. * @type {Light}
  26975. */
  26976. this.light = light;
  26977. /**
  26978. * Overwritten since shadows are updated by default per render.
  26979. *
  26980. * @type {string}
  26981. * @default 'render'
  26982. */
  26983. this.updateBeforeType = NodeUpdateType.RENDER;
  26984. /**
  26985. * This flag can be used for type testing.
  26986. *
  26987. * @type {boolean}
  26988. * @readonly
  26989. * @default true
  26990. */
  26991. this.isShadowBaseNode = true;
  26992. }
  26993. /**
  26994. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  26995. *
  26996. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  26997. */
  26998. setupShadowPosition( { context, material } ) {
  26999. // Use assign inside an Fn()
  27000. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  27001. }
  27002. /**
  27003. * Can be called when the shadow isn't required anymore. That can happen when
  27004. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  27005. * to `false`.
  27006. */
  27007. dispose() {
  27008. this.updateBeforeType = NodeUpdateType.NONE;
  27009. }
  27010. }
  27011. /**
  27012. * TSL object that represents the vertex position in world space during the shadow pass.
  27013. *
  27014. * @tsl
  27015. * @type {Node<vec3>}
  27016. */
  27017. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  27018. /**
  27019. * Saves the state of the given renderer and stores it into the given state object.
  27020. *
  27021. * If not state object is provided, the function creates one.
  27022. *
  27023. * @function
  27024. * @param {Renderer} renderer - The renderer.
  27025. * @param {Object} [state={}] - The state.
  27026. * @return {Object} The state.
  27027. */
  27028. function saveRendererState( renderer, state = {} ) {
  27029. state.toneMapping = renderer.toneMapping;
  27030. state.toneMappingExposure = renderer.toneMappingExposure;
  27031. state.outputColorSpace = renderer.outputColorSpace;
  27032. state.renderTarget = renderer.getRenderTarget();
  27033. state.activeCubeFace = renderer.getActiveCubeFace();
  27034. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27035. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27036. state.pixelRatio = renderer.getPixelRatio();
  27037. state.mrt = renderer.getMRT();
  27038. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27039. state.clearAlpha = renderer.getClearAlpha();
  27040. state.autoClear = renderer.autoClear;
  27041. state.scissorTest = renderer.getScissorTest();
  27042. return state;
  27043. }
  27044. /**
  27045. * Saves the state of the given renderer and stores it into the given state object.
  27046. * Besides, the function also resets the state of the renderer to its default values.
  27047. *
  27048. * If not state object is provided, the function creates one.
  27049. *
  27050. * @function
  27051. * @param {Renderer} renderer - The renderer.
  27052. * @param {Object} [state={}] - The state.
  27053. * @return {Object} The state.
  27054. */
  27055. function resetRendererState( renderer, state ) {
  27056. state = saveRendererState( renderer, state );
  27057. renderer.setMRT( null );
  27058. renderer.setRenderObjectFunction( null );
  27059. renderer.setClearColor( 0x000000, 1 );
  27060. renderer.autoClear = true;
  27061. return state;
  27062. }
  27063. /**
  27064. * Restores the state of the given renderer from the given state object.
  27065. *
  27066. * @function
  27067. * @param {Renderer} renderer - The renderer.
  27068. * @param {Object} state - The state to restore.
  27069. */
  27070. function restoreRendererState( renderer, state ) {
  27071. renderer.toneMapping = state.toneMapping;
  27072. renderer.toneMappingExposure = state.toneMappingExposure;
  27073. renderer.outputColorSpace = state.outputColorSpace;
  27074. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27075. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27076. renderer.setPixelRatio( state.pixelRatio );
  27077. renderer.setMRT( state.mrt );
  27078. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27079. renderer.autoClear = state.autoClear;
  27080. renderer.setScissorTest( state.scissorTest );
  27081. }
  27082. /**
  27083. * Saves the state of the given scene and stores it into the given state object.
  27084. *
  27085. * If not state object is provided, the function creates one.
  27086. *
  27087. * @function
  27088. * @param {Scene} scene - The scene.
  27089. * @param {Object} [state={}] - The state.
  27090. * @return {Object} The state.
  27091. */
  27092. function saveSceneState( scene, state = {} ) {
  27093. state.background = scene.background;
  27094. state.backgroundNode = scene.backgroundNode;
  27095. state.overrideMaterial = scene.overrideMaterial;
  27096. return state;
  27097. }
  27098. /**
  27099. * Saves the state of the given scene and stores it into the given state object.
  27100. * Besides, the function also resets the state of the scene to its default values.
  27101. *
  27102. * If not state object is provided, the function creates one.
  27103. *
  27104. * @function
  27105. * @param {Scene} scene - The scene.
  27106. * @param {Object} [state={}] - The state.
  27107. * @return {Object} The state.
  27108. */
  27109. function resetSceneState( scene, state ) {
  27110. state = saveSceneState( scene, state );
  27111. scene.background = null;
  27112. scene.backgroundNode = null;
  27113. scene.overrideMaterial = null;
  27114. return state;
  27115. }
  27116. /**
  27117. * Restores the state of the given scene from the given state object.
  27118. *
  27119. * @function
  27120. * @param {Scene} scene - The scene.
  27121. * @param {Object} state - The state to restore.
  27122. */
  27123. function restoreSceneState( scene, state ) {
  27124. scene.background = state.background;
  27125. scene.backgroundNode = state.backgroundNode;
  27126. scene.overrideMaterial = state.overrideMaterial;
  27127. }
  27128. /**
  27129. * Saves the state of the given renderer and scene and stores it into the given state object.
  27130. *
  27131. * If not state object is provided, the function creates one.
  27132. *
  27133. * @function
  27134. * @param {Renderer} renderer - The renderer.
  27135. * @param {Scene} scene - The scene.
  27136. * @param {Object} [state={}] - The state.
  27137. * @return {Object} The state.
  27138. */
  27139. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  27140. state = saveRendererState( renderer, state );
  27141. state = saveSceneState( scene, state );
  27142. return state;
  27143. }
  27144. /**
  27145. * Saves the state of the given renderer and scene and stores it into the given state object.
  27146. * Besides, the function also resets the state of the renderer and scene to its default values.
  27147. *
  27148. * If not state object is provided, the function creates one.
  27149. *
  27150. * @function
  27151. * @param {Renderer} renderer - The renderer.
  27152. * @param {Scene} scene - The scene.
  27153. * @param {Object} [state={}] - The state.
  27154. * @return {Object} The state.
  27155. */
  27156. function resetRendererAndSceneState( renderer, scene, state ) {
  27157. state = resetRendererState( renderer, state );
  27158. state = resetSceneState( scene, state );
  27159. return state;
  27160. }
  27161. /**
  27162. * Restores the state of the given renderer and scene from the given state object.
  27163. *
  27164. * @function
  27165. * @param {Renderer} renderer - The renderer.
  27166. * @param {Scene} scene - The scene.
  27167. * @param {Object} state - The state to restore.
  27168. */
  27169. function restoreRendererAndSceneState( renderer, scene, state ) {
  27170. restoreRendererState( renderer, state );
  27171. restoreSceneState( scene, state );
  27172. }
  27173. var RendererUtils = /*#__PURE__*/Object.freeze({
  27174. __proto__: null,
  27175. resetRendererAndSceneState: resetRendererAndSceneState,
  27176. resetRendererState: resetRendererState,
  27177. resetSceneState: resetSceneState,
  27178. restoreRendererAndSceneState: restoreRendererAndSceneState,
  27179. restoreRendererState: restoreRendererState,
  27180. restoreSceneState: restoreSceneState,
  27181. saveRendererAndSceneState: saveRendererAndSceneState,
  27182. saveRendererState: saveRendererState,
  27183. saveSceneState: saveSceneState
  27184. });
  27185. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  27186. /**
  27187. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  27188. * with a binary `[0,1]` result.
  27189. *
  27190. * @method
  27191. * @param {Object} inputs - The input parameter object.
  27192. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27193. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27194. * @return {Node<float>} The filtering result.
  27195. */
  27196. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27197. let basic = texture( depthTexture, shadowCoord.xy ).label( 't_basic' );
  27198. if ( depthTexture.isDepthArrayTexture ) {
  27199. basic = basic.depth( depthLayer );
  27200. }
  27201. return basic.compare( shadowCoord.z );
  27202. } );
  27203. /**
  27204. * A shadow filtering function performing PCF filtering.
  27205. *
  27206. * @method
  27207. * @param {Object} inputs - The input parameter object.
  27208. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27209. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27210. * @param {LightShadow} inputs.shadow - The light shadow.
  27211. * @return {Node<float>} The filtering result.
  27212. */
  27213. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27214. const depthCompare = ( uv, compare ) => {
  27215. let depth = texture( depthTexture, uv );
  27216. if ( depthTexture.isDepthArrayTexture ) {
  27217. depth = depth.depth( depthLayer );
  27218. }
  27219. return depth.compare( compare );
  27220. };
  27221. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27222. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27223. const texelSize = vec2( 1 ).div( mapSize );
  27224. const dx0 = texelSize.x.negate().mul( radius );
  27225. const dy0 = texelSize.y.negate().mul( radius );
  27226. const dx1 = texelSize.x.mul( radius );
  27227. const dy1 = texelSize.y.mul( radius );
  27228. const dx2 = dx0.div( 2 );
  27229. const dy2 = dy0.div( 2 );
  27230. const dx3 = dx1.div( 2 );
  27231. const dy3 = dy1.div( 2 );
  27232. return add(
  27233. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  27234. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  27235. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  27236. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  27237. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  27238. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  27239. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  27240. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  27241. depthCompare( shadowCoord.xy, shadowCoord.z ),
  27242. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  27243. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  27244. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  27245. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  27246. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  27247. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  27248. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  27249. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  27250. ).mul( 1 / 17 );
  27251. } );
  27252. /**
  27253. * A shadow filtering function performing PCF soft filtering.
  27254. *
  27255. * @method
  27256. * @param {Object} inputs - The input parameter object.
  27257. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27258. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27259. * @param {LightShadow} inputs.shadow - The light shadow.
  27260. * @return {Node<float>} The filtering result.
  27261. */
  27262. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27263. const depthCompare = ( uv, compare ) => {
  27264. let depth = texture( depthTexture, uv );
  27265. if ( depthTexture.isDepthArrayTexture ) {
  27266. depth = depth.depth( depthLayer );
  27267. }
  27268. return depth.compare( compare );
  27269. };
  27270. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27271. const texelSize = vec2( 1 ).div( mapSize );
  27272. const dx = texelSize.x;
  27273. const dy = texelSize.y;
  27274. const uv = shadowCoord.xy;
  27275. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  27276. uv.subAssign( f.mul( texelSize ) );
  27277. return add(
  27278. depthCompare( uv, shadowCoord.z ),
  27279. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  27280. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  27281. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  27282. mix(
  27283. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  27284. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  27285. f.x
  27286. ),
  27287. mix(
  27288. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  27289. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  27290. f.x
  27291. ),
  27292. mix(
  27293. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  27294. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  27295. f.y
  27296. ),
  27297. mix(
  27298. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  27299. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  27300. f.y
  27301. ),
  27302. mix(
  27303. mix(
  27304. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  27305. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  27306. f.x
  27307. ),
  27308. mix(
  27309. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  27310. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  27311. f.x
  27312. ),
  27313. f.y
  27314. )
  27315. ).mul( 1 / 9 );
  27316. } );
  27317. /**
  27318. * A shadow filtering function performing VSM filtering.
  27319. *
  27320. * @method
  27321. * @param {Object} inputs - The input parameter object.
  27322. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27323. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27324. * @return {Node<float>} The filtering result.
  27325. */
  27326. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27327. const occlusion = float( 1 ).toVar();
  27328. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  27329. if ( depthTexture.isDepthArrayTexture || depthTexture.isDataArrayTexture ) {
  27330. distribution = distribution.depth( depthLayer );
  27331. }
  27332. distribution = distribution.rg;
  27333. const hardShadow = step( shadowCoord.z, distribution.x );
  27334. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  27335. const distance = shadowCoord.z.sub( distribution.x );
  27336. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  27337. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  27338. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  27339. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  27340. } );
  27341. return occlusion;
  27342. } );
  27343. //
  27344. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  27345. let dist = positionWorld.sub( position ).length();
  27346. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  27347. dist = dist.saturate(); // clamp to [ 0, 1 ]
  27348. return dist;
  27349. } );
  27350. const linearShadowDistance = ( light ) => {
  27351. const camera = light.shadow.camera;
  27352. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  27353. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  27354. const referencePosition = objectPosition( light );
  27355. return linearDistance( referencePosition, nearDistance, farDistance );
  27356. };
  27357. /**
  27358. * Retrieves or creates a shadow material for the given light source.
  27359. *
  27360. * This function checks if a shadow material already exists for the provided light.
  27361. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  27362. * in the `shadowMaterialLib` for future use.
  27363. *
  27364. * @param {Light} light - The light source for which the shadow material is needed.
  27365. * If the light is a point light, a depth node is calculated
  27366. * using the linear shadow distance.
  27367. * @returns {NodeMaterial} The shadow material associated with the given light.
  27368. */
  27369. const getShadowMaterial = ( light ) => {
  27370. let material = shadowMaterialLib.get( light );
  27371. if ( material === undefined ) {
  27372. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  27373. material = new NodeMaterial();
  27374. material.colorNode = vec4( 0, 0, 0, 1 );
  27375. material.depthNode = depthNode;
  27376. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  27377. material.name = 'ShadowMaterial';
  27378. material.fog = false;
  27379. shadowMaterialLib.set( light, material );
  27380. }
  27381. return material;
  27382. };
  27383. //
  27384. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  27385. const _shadowRenderObjectKeys = [];
  27386. /**
  27387. * Creates a function to render shadow objects in a scene.
  27388. *
  27389. * @param {Renderer} renderer - The renderer.
  27390. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  27391. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  27392. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  27393. * @return {Function} A function that renders shadow objects.
  27394. *
  27395. * The returned function has the following parameters:
  27396. * @param {Object3D} object - The 3D object to render.
  27397. * @param {Scene} scene - The scene containing the object.
  27398. * @param {Camera} _camera - The camera used for rendering.
  27399. * @param {BufferGeometry} geometry - The geometry of the object.
  27400. * @param {Material} material - The material of the object.
  27401. * @param {Group} group - The group the object belongs to.
  27402. * @param {...any} params - Additional parameters for rendering.
  27403. */
  27404. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  27405. _shadowRenderObjectKeys[ 0 ] = renderer;
  27406. _shadowRenderObjectKeys[ 1 ] = shadow;
  27407. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  27408. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  27409. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  27410. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  27411. if ( useVelocity ) {
  27412. getDataFromObject( object ).useVelocity = true;
  27413. }
  27414. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27415. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  27416. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27417. }
  27418. };
  27419. renderObjectFunction.shadowType = shadowType;
  27420. renderObjectFunction.useVelocity = useVelocity;
  27421. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  27422. }
  27423. _shadowRenderObjectKeys[ 0 ] = null;
  27424. _shadowRenderObjectKeys[ 1 ] = null;
  27425. return renderObjectFunction;
  27426. };
  27427. /**
  27428. * Represents the shader code for the first VSM render pass.
  27429. *
  27430. * @method
  27431. * @param {Object} inputs - The input parameter object.
  27432. * @param {Node<float>} inputs.samples - The number of samples
  27433. * @param {Node<float>} inputs.radius - The radius.
  27434. * @param {Node<float>} inputs.size - The size.
  27435. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  27436. * @return {Node<vec2>} The VSM output.
  27437. */
  27438. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27439. const mean = float( 0 ).toVar( 'meanVertical' );
  27440. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  27441. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27442. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27443. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27444. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27445. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  27446. if ( shadowPass.value.isDepthArrayTexture || shadowPass.value.isDataArrayTexture ) {
  27447. depth = depth.depth( depthLayer );
  27448. }
  27449. depth = depth.x;
  27450. mean.addAssign( depth );
  27451. squaredMean.addAssign( depth.mul( depth ) );
  27452. } );
  27453. mean.divAssign( samples );
  27454. squaredMean.divAssign( samples );
  27455. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27456. return vec2( mean, std_dev );
  27457. } );
  27458. /**
  27459. * Represents the shader code for the second VSM render pass.
  27460. *
  27461. * @method
  27462. * @param {Object} inputs - The input parameter object.
  27463. * @param {Node<float>} inputs.samples - The number of samples
  27464. * @param {Node<float>} inputs.radius - The radius.
  27465. * @param {Node<float>} inputs.size - The size.
  27466. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  27467. * @return {Node<vec2>} The VSM output.
  27468. */
  27469. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27470. const mean = float( 0 ).toVar( 'meanHorizontal' );
  27471. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  27472. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27473. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27474. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27475. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27476. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  27477. if ( shadowPass.value.isDepthArrayTexture || shadowPass.value.isDataArrayTexture ) {
  27478. distribution = distribution.depth( depthLayer );
  27479. }
  27480. mean.addAssign( distribution.x );
  27481. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  27482. } );
  27483. mean.divAssign( samples );
  27484. squaredMean.divAssign( samples );
  27485. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27486. return vec2( mean, std_dev );
  27487. } );
  27488. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  27489. //
  27490. let _rendererState;
  27491. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  27492. /**
  27493. * Represents the default shadow implementation for lighting nodes.
  27494. *
  27495. * @augments ShadowBaseNode
  27496. */
  27497. class ShadowNode extends ShadowBaseNode {
  27498. static get type() {
  27499. return 'ShadowNode';
  27500. }
  27501. /**
  27502. * Constructs a new shadow node.
  27503. *
  27504. * @param {Light} light - The shadow casting light.
  27505. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  27506. */
  27507. constructor( light, shadow = null ) {
  27508. super( light );
  27509. /**
  27510. * The light shadow which defines the properties light's
  27511. * shadow.
  27512. *
  27513. * @type {?LightShadow}
  27514. * @default null
  27515. */
  27516. this.shadow = shadow || light.shadow;
  27517. /**
  27518. * A reference to the shadow map which is a render target.
  27519. *
  27520. * @type {?RenderTarget}
  27521. * @default null
  27522. */
  27523. this.shadowMap = null;
  27524. /**
  27525. * Only relevant for VSM shadows. Render target for the
  27526. * first VSM render pass.
  27527. *
  27528. * @type {?RenderTarget}
  27529. * @default null
  27530. */
  27531. this.vsmShadowMapVertical = null;
  27532. /**
  27533. * Only relevant for VSM shadows. Render target for the
  27534. * second VSM render pass.
  27535. *
  27536. * @type {?RenderTarget}
  27537. * @default null
  27538. */
  27539. this.vsmShadowMapHorizontal = null;
  27540. /**
  27541. * Only relevant for VSM shadows. Node material which
  27542. * is used to render the first VSM pass.
  27543. *
  27544. * @type {?NodeMaterial}
  27545. * @default null
  27546. */
  27547. this.vsmMaterialVertical = null;
  27548. /**
  27549. * Only relevant for VSM shadows. Node material which
  27550. * is used to render the second VSM pass.
  27551. *
  27552. * @type {?NodeMaterial}
  27553. * @default null
  27554. */
  27555. this.vsmMaterialHorizontal = null;
  27556. /**
  27557. * A reference to the output node which defines the
  27558. * final result of this shadow node.
  27559. *
  27560. * @type {?Node}
  27561. * @private
  27562. * @default null
  27563. */
  27564. this._node = null;
  27565. this._cameraFrameId = new WeakMap();
  27566. /**
  27567. * This flag can be used for type testing.
  27568. *
  27569. * @type {boolean}
  27570. * @readonly
  27571. * @default true
  27572. */
  27573. this.isShadowNode = true;
  27574. /**
  27575. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  27576. *
  27577. * @type {number}
  27578. * @readonly
  27579. * @default true
  27580. */
  27581. this.depthLayer = 0;
  27582. }
  27583. /**
  27584. * Setups the shadow filtering.
  27585. *
  27586. * @param {NodeBuilder} builder - A reference to the current node builder.
  27587. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  27588. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  27589. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27590. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  27591. * @param {LightShadow} inputs.shadow - The light shadow.
  27592. * @return {Node<float>} The result node of the shadow filtering.
  27593. */
  27594. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  27595. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  27596. .and( shadowCoord.x.lessThanEqual( 1 ) )
  27597. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  27598. .and( shadowCoord.y.lessThanEqual( 1 ) )
  27599. .and( shadowCoord.z.lessThanEqual( 1 ) );
  27600. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  27601. return frustumTest.select( shadowNode, float( 1 ) );
  27602. }
  27603. /**
  27604. * Setups the shadow coordinates.
  27605. *
  27606. * @param {NodeBuilder} builder - A reference to the current node builder.
  27607. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  27608. * @return {Node<vec3>} The shadow coordinates.
  27609. */
  27610. setupShadowCoord( builder, shadowPosition ) {
  27611. const { shadow } = this;
  27612. const { renderer } = builder;
  27613. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27614. let shadowCoord = shadowPosition;
  27615. let coordZ;
  27616. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  27617. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  27618. coordZ = shadowCoord.z;
  27619. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  27620. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  27621. }
  27622. } else {
  27623. const w = shadowCoord.w;
  27624. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  27625. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  27626. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  27627. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  27628. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  27629. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  27630. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  27631. }
  27632. shadowCoord = vec3(
  27633. shadowCoord.x,
  27634. shadowCoord.y.oneMinus(), // follow webgpu standards
  27635. coordZ.add( bias )
  27636. );
  27637. return shadowCoord;
  27638. }
  27639. /**
  27640. * Returns the shadow filtering function for the given shadow type.
  27641. *
  27642. * @param {number} type - The shadow type.
  27643. * @return {Function} The filtering function.
  27644. */
  27645. getShadowFilterFn( type ) {
  27646. return _shadowFilterLib[ type ];
  27647. }
  27648. setupRenderTarget( shadow, builder ) {
  27649. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  27650. depthTexture.name = 'ShadowDepthTexture';
  27651. depthTexture.compareFunction = LessCompare;
  27652. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  27653. shadowMap.texture.name = 'ShadowMap';
  27654. shadowMap.texture.type = shadow.mapType;
  27655. shadowMap.depthTexture = depthTexture;
  27656. return { shadowMap, depthTexture };
  27657. }
  27658. /**
  27659. * Setups the shadow output node.
  27660. *
  27661. * @param {NodeBuilder} builder - A reference to the current node builder.
  27662. * @return {Node<vec3>} The shadow output node.
  27663. */
  27664. setupShadow( builder ) {
  27665. const { renderer } = builder;
  27666. const { light, shadow } = this;
  27667. const shadowMapType = renderer.shadowMap.type;
  27668. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  27669. shadow.camera.updateProjectionMatrix();
  27670. // VSM
  27671. if ( shadowMapType === VSMShadowMap ) {
  27672. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  27673. if ( shadowMap.isRenderTargetArray ) {
  27674. if ( ! shadowMap._vsmShadowMapVertical ) {
  27675. shadowMap._vsmShadowMapVertical = builder.createRenderTargetArray( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27676. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  27677. }
  27678. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  27679. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  27680. shadowMap._vsmShadowMapHorizontal = builder.createRenderTargetArray( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27681. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  27682. }
  27683. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  27684. } else {
  27685. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27686. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  27687. }
  27688. let shadowPassVertical = texture( depthTexture );
  27689. if ( depthTexture.isDepthArrayTexture ) {
  27690. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  27691. }
  27692. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  27693. if ( depthTexture.isDepthArrayTexture ) {
  27694. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  27695. }
  27696. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  27697. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27698. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27699. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  27700. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  27701. material.name = 'VSMVertical';
  27702. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  27703. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  27704. material.name = 'VSMHorizontal';
  27705. }
  27706. //
  27707. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  27708. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  27709. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  27710. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  27711. //
  27712. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  27713. if ( filterFn === null ) {
  27714. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  27715. }
  27716. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  27717. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  27718. let shadowColor = texture( shadowMap.texture, shadowCoord );
  27719. if ( depthTexture.isDepthArrayTexture ) {
  27720. shadowColor = shadowColor.depth( this.depthLayer );
  27721. }
  27722. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  27723. this.shadowMap = shadowMap;
  27724. this.shadow.map = shadowMap;
  27725. return shadowOutput;
  27726. }
  27727. /**
  27728. * The implementation performs the setup of the output node. An output is only
  27729. * produces if shadow mapping is globally enabled in the renderer.
  27730. *
  27731. * @param {NodeBuilder} builder - A reference to the current node builder.
  27732. * @return {ShaderCallNodeInternal} The output node.
  27733. */
  27734. setup( builder ) {
  27735. if ( builder.renderer.shadowMap.enabled === false ) return;
  27736. return Fn( () => {
  27737. let node = this._node;
  27738. this.setupShadowPosition( builder );
  27739. if ( node === null ) {
  27740. this._node = node = this.setupShadow( builder );
  27741. }
  27742. if ( builder.material.shadowNode ) { // @deprecated, r171
  27743. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  27744. }
  27745. if ( builder.material.receivedShadowNode ) {
  27746. node = builder.material.receivedShadowNode( node );
  27747. }
  27748. return node;
  27749. } )();
  27750. }
  27751. /**
  27752. * Renders the shadow. The logic of this function could be included
  27753. * into {@link ShadowNode#updateShadow} however more specialized shadow
  27754. * nodes might require a custom shadow map rendering. By having a
  27755. * dedicated method, it's easier to overwrite the default behavior.
  27756. *
  27757. * @param {NodeFrame} frame - A reference to the current node frame.
  27758. */
  27759. renderShadow( frame ) {
  27760. const { shadow, shadowMap, light } = this;
  27761. const { renderer, scene } = frame;
  27762. shadow.updateMatrices( light );
  27763. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  27764. renderer.render( scene, shadow.camera );
  27765. }
  27766. /**
  27767. * Updates the shadow.
  27768. *
  27769. * @param {NodeFrame} frame - A reference to the current node frame.
  27770. */
  27771. updateShadow( frame ) {
  27772. const { shadowMap, light, shadow } = this;
  27773. const { renderer, scene, camera } = frame;
  27774. const shadowType = renderer.shadowMap.type;
  27775. const depthVersion = shadowMap.depthTexture.version;
  27776. this._depthVersionCached = depthVersion;
  27777. const _shadowCameraLayer = shadow.camera.layers.mask;
  27778. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  27779. shadow.camera.layers.mask = camera.layers.mask;
  27780. }
  27781. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  27782. const currentMRT = renderer.getMRT();
  27783. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  27784. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  27785. scene.overrideMaterial = getShadowMaterial( light );
  27786. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  27787. renderer.setClearColor( 0x000000, 0 );
  27788. renderer.setRenderTarget( shadowMap );
  27789. this.renderShadow( frame );
  27790. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  27791. // vsm blur pass
  27792. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  27793. this.vsmPass( renderer );
  27794. }
  27795. shadow.camera.layers.mask = _shadowCameraLayer;
  27796. restoreRendererAndSceneState( renderer, scene, _rendererState );
  27797. }
  27798. /**
  27799. * For VSM additional render passes are required.
  27800. *
  27801. * @param {Renderer} renderer - A reference to the current renderer.
  27802. */
  27803. vsmPass( renderer ) {
  27804. const { shadow } = this;
  27805. const depth = this.shadowMap.depth;
  27806. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  27807. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  27808. renderer.setRenderTarget( this.vsmShadowMapVertical );
  27809. _quadMesh.material = this.vsmMaterialVertical;
  27810. _quadMesh.render( renderer );
  27811. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  27812. _quadMesh.material = this.vsmMaterialHorizontal;
  27813. _quadMesh.render( renderer );
  27814. }
  27815. /**
  27816. * Frees the internal resources of this shadow node.
  27817. */
  27818. dispose() {
  27819. this.shadowMap.dispose();
  27820. this.shadowMap = null;
  27821. if ( this.vsmShadowMapVertical !== null ) {
  27822. this.vsmShadowMapVertical.dispose();
  27823. this.vsmShadowMapVertical = null;
  27824. this.vsmMaterialVertical.dispose();
  27825. this.vsmMaterialVertical = null;
  27826. }
  27827. if ( this.vsmShadowMapHorizontal !== null ) {
  27828. this.vsmShadowMapHorizontal.dispose();
  27829. this.vsmShadowMapHorizontal = null;
  27830. this.vsmMaterialHorizontal.dispose();
  27831. this.vsmMaterialHorizontal = null;
  27832. }
  27833. super.dispose();
  27834. }
  27835. /**
  27836. * The implementation performs the update of the shadow map if necessary.
  27837. *
  27838. * @param {NodeFrame} frame - A reference to the current node frame.
  27839. */
  27840. updateBefore( frame ) {
  27841. const { shadow } = this;
  27842. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  27843. if ( needsUpdate ) {
  27844. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  27845. needsUpdate = false;
  27846. }
  27847. this._cameraFrameId[ frame.camera ] = frame.frameId;
  27848. }
  27849. if ( needsUpdate ) {
  27850. this.updateShadow( frame );
  27851. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  27852. shadow.needsUpdate = false;
  27853. }
  27854. }
  27855. }
  27856. }
  27857. /**
  27858. * TSL function for creating an instance of `ShadowNode`.
  27859. *
  27860. * @tsl
  27861. * @function
  27862. * @param {Light} light - The shadow casting light.
  27863. * @param {?LightShadow} [shadow] - The light shadow.
  27864. * @return {ShadowNode} The created shadow node.
  27865. */
  27866. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  27867. const _clearColor$1 = /*@__PURE__*/ new Color();
  27868. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  27869. // vector suitable for 2D texture mapping. This code uses the following layout for the
  27870. // 2D texture:
  27871. //
  27872. // xzXZ
  27873. // y Y
  27874. //
  27875. // Y - Positive y direction
  27876. // y - Negative y direction
  27877. // X - Positive x direction
  27878. // x - Negative x direction
  27879. // Z - Positive z direction
  27880. // z - Negative z direction
  27881. //
  27882. // Source and test bed:
  27883. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  27884. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  27885. const v = pos.toVar();
  27886. // Number of texels to avoid at the edge of each square
  27887. const absV = abs( v );
  27888. // Intersect unit cube
  27889. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  27890. absV.mulAssign( scaleToCube );
  27891. // Apply scale to avoid seams
  27892. // two texels less per square (one texel will do for NEAREST)
  27893. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  27894. // Unwrap
  27895. // space: -1 ... 1 range for each square
  27896. //
  27897. // #X## dim := ( 4 , 2 )
  27898. // # # center := ( 1 , 1 )
  27899. const planar = vec2( v.xy ).toVar();
  27900. const almostATexel = texelSizeY.mul( 1.5 );
  27901. const almostOne = almostATexel.oneMinus();
  27902. If( absV.z.greaterThanEqual( almostOne ), () => {
  27903. If( v.z.greaterThan( 0.0 ), () => {
  27904. planar.x.assign( sub( 4.0, v.x ) );
  27905. } );
  27906. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  27907. const signX = sign( v.x );
  27908. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  27909. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  27910. const signY = sign( v.y );
  27911. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  27912. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  27913. } );
  27914. // Transform to UV space
  27915. // scale := 0.5 / dim
  27916. // translate := ( center + 0.5 ) / dim
  27917. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  27918. } ).setLayout( {
  27919. name: 'cubeToUV',
  27920. type: 'vec2',
  27921. inputs: [
  27922. { name: 'pos', type: 'vec3' },
  27923. { name: 'texelSizeY', type: 'float' }
  27924. ]
  27925. } );
  27926. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  27927. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  27928. } );
  27929. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  27930. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27931. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  27932. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  27933. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  27934. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  27935. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  27936. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  27937. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  27938. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  27939. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  27940. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  27941. .mul( 1.0 / 9.0 );
  27942. } );
  27943. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  27944. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  27945. // the vector from the light to the world-space position of the fragment.
  27946. const lightToPosition = shadowCoord.xyz.toVar();
  27947. const lightToPositionLength = lightToPosition.length();
  27948. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  27949. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  27950. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27951. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  27952. const result = float( 1.0 ).toVar();
  27953. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  27954. // dp = normalized distance from light to fragment position
  27955. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  27956. dp.addAssign( bias );
  27957. // bd3D = base direction 3D
  27958. const bd3D = lightToPosition.normalize();
  27959. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  27960. // percentage-closer filtering
  27961. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  27962. } );
  27963. return result;
  27964. } );
  27965. const _viewport = /*@__PURE__*/ new Vector4();
  27966. const _viewportSize = /*@__PURE__*/ new Vector2();
  27967. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  27968. /**
  27969. * Represents the shadow implementation for point light nodes.
  27970. *
  27971. * @augments ShadowNode
  27972. */
  27973. class PointShadowNode extends ShadowNode {
  27974. static get type() {
  27975. return 'PointShadowNode';
  27976. }
  27977. /**
  27978. * Constructs a new point shadow node.
  27979. *
  27980. * @param {PointLight} light - The shadow casting point light.
  27981. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  27982. */
  27983. constructor( light, shadow = null ) {
  27984. super( light, shadow );
  27985. }
  27986. /**
  27987. * Overwrites the default implementation to return point light shadow specific
  27988. * filtering functions.
  27989. *
  27990. * @param {number} type - The shadow type.
  27991. * @return {Function} The filtering function.
  27992. */
  27993. getShadowFilterFn( type ) {
  27994. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  27995. }
  27996. /**
  27997. * Overwrites the default implementation so the unaltered shadow position is used.
  27998. *
  27999. * @param {NodeBuilder} builder - A reference to the current node builder.
  28000. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28001. * @return {Node<vec3>} The shadow coordinates.
  28002. */
  28003. setupShadowCoord( builder, shadowPosition ) {
  28004. return shadowPosition;
  28005. }
  28006. /**
  28007. * Overwrites the default implementation to only use point light specific
  28008. * shadow filter functions.
  28009. *
  28010. * @param {NodeBuilder} builder - A reference to the current node builder.
  28011. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28012. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28013. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  28014. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28015. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28016. * @param {LightShadow} inputs.shadow - The light shadow.
  28017. * @return {Node<float>} The result node of the shadow filtering.
  28018. */
  28019. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  28020. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  28021. }
  28022. /**
  28023. * Overwrites the default implementation with point light specific
  28024. * rendering code.
  28025. *
  28026. * @param {NodeFrame} frame - A reference to the current node frame.
  28027. */
  28028. renderShadow( frame ) {
  28029. const { shadow, shadowMap, light } = this;
  28030. const { renderer, scene } = frame;
  28031. const shadowFrameExtents = shadow.getFrameExtents();
  28032. _shadowMapSize.copy( shadow.mapSize );
  28033. _shadowMapSize.multiply( shadowFrameExtents );
  28034. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  28035. _viewportSize.copy( shadow.mapSize );
  28036. //
  28037. const previousAutoClear = renderer.autoClear;
  28038. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  28039. const previousClearAlpha = renderer.getClearAlpha();
  28040. renderer.autoClear = false;
  28041. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  28042. renderer.clear();
  28043. const viewportCount = shadow.getViewportCount();
  28044. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  28045. const viewport = shadow.getViewport( vp );
  28046. const x = _viewportSize.x * viewport.x;
  28047. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  28048. _viewport.set(
  28049. x,
  28050. y,
  28051. _viewportSize.x * viewport.z,
  28052. _viewportSize.y * viewport.w
  28053. );
  28054. shadowMap.viewport.copy( _viewport );
  28055. shadow.updateMatrices( light, vp );
  28056. renderer.render( scene, shadow.camera );
  28057. }
  28058. //
  28059. renderer.autoClear = previousAutoClear;
  28060. renderer.setClearColor( previousClearColor, previousClearAlpha );
  28061. }
  28062. }
  28063. /**
  28064. * TSL function for creating an instance of `PointShadowNode`.
  28065. *
  28066. * @tsl
  28067. * @function
  28068. * @param {PointLight} light - The shadow casting point light.
  28069. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28070. * @return {PointShadowNode} The created point shadow node.
  28071. */
  28072. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  28073. /**
  28074. * Base class for analytic light nodes.
  28075. *
  28076. * @augments LightingNode
  28077. */
  28078. class AnalyticLightNode extends LightingNode {
  28079. static get type() {
  28080. return 'AnalyticLightNode';
  28081. }
  28082. /**
  28083. * Constructs a new analytic light node.
  28084. *
  28085. * @param {?Light} [light=null] - The light source.
  28086. */
  28087. constructor( light = null ) {
  28088. super();
  28089. /**
  28090. * The light source.
  28091. *
  28092. * @type {?Light}
  28093. * @default null
  28094. */
  28095. this.light = light;
  28096. /**
  28097. * The light's color value.
  28098. *
  28099. * @type {Color}
  28100. */
  28101. this.color = new Color();
  28102. /**
  28103. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  28104. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  28105. *
  28106. * @type {Node}
  28107. */
  28108. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  28109. /**
  28110. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  28111. * The final color node is represented by a different node when using shadows.
  28112. *
  28113. * @type {?Node}
  28114. * @default null
  28115. */
  28116. this.baseColorNode = null;
  28117. /**
  28118. * Represents the light's shadow.
  28119. *
  28120. * @type {?ShadowNode}
  28121. * @default null
  28122. */
  28123. this.shadowNode = null;
  28124. /**
  28125. * Represents the light's shadow color.
  28126. *
  28127. * @type {?Node}
  28128. * @default null
  28129. */
  28130. this.shadowColorNode = null;
  28131. /**
  28132. * This flag can be used for type testing.
  28133. *
  28134. * @type {boolean}
  28135. * @readonly
  28136. * @default true
  28137. */
  28138. this.isAnalyticLightNode = true;
  28139. /**
  28140. * Overwritten since analytic light nodes are updated
  28141. * once per frame.
  28142. *
  28143. * @type {string}
  28144. * @default 'frame'
  28145. */
  28146. this.updateType = NodeUpdateType.FRAME;
  28147. }
  28148. /**
  28149. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  28150. * `light.id` and `light.castShadow` into the cache key.
  28151. *
  28152. * @return {number} The custom cache key.
  28153. */
  28154. customCacheKey() {
  28155. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  28156. }
  28157. getHash() {
  28158. return this.light.uuid;
  28159. }
  28160. getLightVector( builder ) {
  28161. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  28162. }
  28163. /**
  28164. * Sets up the direct lighting for the analytic light node.
  28165. *
  28166. * @abstract
  28167. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28168. * @return {Object|undefined} The direct light data (color and direction).
  28169. */
  28170. setupDirect( /*builder*/ ) { }
  28171. /**
  28172. * Sets up the direct rect area lighting for the analytic light node.
  28173. *
  28174. * @abstract
  28175. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28176. * @return {Object|undefined} The direct rect area light data.
  28177. */
  28178. setupDirectRectArea( /*builder*/ ) { }
  28179. /**
  28180. * Setups the shadow node for this light. The method exists so concrete light classes
  28181. * can setup different types of shadow nodes.
  28182. *
  28183. * @return {ShadowNode} The created shadow node.
  28184. */
  28185. setupShadowNode() {
  28186. return shadow( this.light );
  28187. }
  28188. /**
  28189. * Setups the shadow for this light. This method is only executed if the light
  28190. * cast shadows and the current build object receives shadows. It incorporates
  28191. * shadows into the lighting computation.
  28192. *
  28193. * @param {NodeBuilder} builder - The current node builder.
  28194. */
  28195. setupShadow( builder ) {
  28196. const { renderer } = builder;
  28197. if ( renderer.shadowMap.enabled === false ) return;
  28198. let shadowColorNode = this.shadowColorNode;
  28199. if ( shadowColorNode === null ) {
  28200. const customShadowNode = this.light.shadow.shadowNode;
  28201. let shadowNode;
  28202. if ( customShadowNode !== undefined ) {
  28203. shadowNode = nodeObject( customShadowNode );
  28204. } else {
  28205. shadowNode = this.setupShadowNode();
  28206. }
  28207. this.shadowNode = shadowNode;
  28208. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  28209. this.baseColorNode = this.colorNode;
  28210. }
  28211. //
  28212. this.colorNode = shadowColorNode;
  28213. }
  28214. /**
  28215. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  28216. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  28217. * invocate the respective interface methods.
  28218. *
  28219. * @param {NodeBuilder} builder - The current node builder.
  28220. */
  28221. setup( builder ) {
  28222. this.colorNode = this.baseColorNode || this.colorNode;
  28223. if ( this.light.castShadow ) {
  28224. if ( builder.object.receiveShadow ) {
  28225. this.setupShadow( builder );
  28226. }
  28227. } else if ( this.shadowNode !== null ) {
  28228. this.shadowNode.dispose();
  28229. this.shadowNode = null;
  28230. this.shadowColorNode = null;
  28231. }
  28232. const directLightData = this.setupDirect( builder );
  28233. const directRectAreaLightData = this.setupDirectRectArea( builder );
  28234. if ( directLightData ) {
  28235. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  28236. }
  28237. if ( directRectAreaLightData ) {
  28238. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  28239. }
  28240. }
  28241. /**
  28242. * The update method is used to update light uniforms per frame.
  28243. * Potentially overwritten in concrete light nodes to update light
  28244. * specific uniforms.
  28245. *
  28246. * @param {NodeFrame} frame - A reference to the current node frame.
  28247. */
  28248. update( /*frame*/ ) {
  28249. const { light } = this;
  28250. this.color.copy( light.color ).multiplyScalar( light.intensity );
  28251. }
  28252. }
  28253. /**
  28254. * Represents a `discard` shader operation in TSL.
  28255. *
  28256. * @method
  28257. * @param {Object} inputs - The input parameter object.
  28258. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  28259. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  28260. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  28261. * @return {Node<float>} The distance falloff.
  28262. */
  28263. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  28264. // based upon Frostbite 3 Moving to Physically-based Rendering
  28265. // page 32, equation 26: E[window1]
  28266. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28267. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  28268. return cutoffDistance.greaterThan( 0 ).select(
  28269. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  28270. distanceFalloff
  28271. );
  28272. } ); // validated
  28273. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  28274. const lightDirection = lightVector.normalize();
  28275. const lightDistance = lightVector.length();
  28276. const attenuation = getDistanceAttenuation( {
  28277. lightDistance,
  28278. cutoffDistance,
  28279. decayExponent
  28280. } );
  28281. const lightColor = color.mul( attenuation );
  28282. return { lightDirection, lightColor };
  28283. };
  28284. /**
  28285. * Module for representing point lights as nodes.
  28286. *
  28287. * @augments AnalyticLightNode
  28288. */
  28289. class PointLightNode extends AnalyticLightNode {
  28290. static get type() {
  28291. return 'PointLightNode';
  28292. }
  28293. /**
  28294. * Constructs a new point light node.
  28295. *
  28296. * @param {?PointLight} [light=null] - The point light source.
  28297. */
  28298. constructor( light = null ) {
  28299. super( light );
  28300. /**
  28301. * Uniform node representing the cutoff distance.
  28302. *
  28303. * @type {UniformNode<float>}
  28304. */
  28305. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  28306. /**
  28307. * Uniform node representing the decay exponent.
  28308. *
  28309. * @type {UniformNode<float>}
  28310. */
  28311. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  28312. }
  28313. /**
  28314. * Overwritten to updated point light specific uniforms.
  28315. *
  28316. * @param {NodeFrame} frame - A reference to the current node frame.
  28317. */
  28318. update( frame ) {
  28319. const { light } = this;
  28320. super.update( frame );
  28321. this.cutoffDistanceNode.value = light.distance;
  28322. this.decayExponentNode.value = light.decay;
  28323. }
  28324. /**
  28325. * Overwritten to setup point light specific shadow.
  28326. *
  28327. * @return {PointShadowNode}
  28328. */
  28329. setupShadowNode() {
  28330. return pointShadow( this.light );
  28331. }
  28332. setupDirect( builder ) {
  28333. return directPointLight( {
  28334. color: this.colorNode,
  28335. lightVector: this.getLightVector( builder ),
  28336. cutoffDistance: this.cutoffDistanceNode,
  28337. decayExponent: this.decayExponentNode
  28338. } );
  28339. }
  28340. }
  28341. /**
  28342. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  28343. *
  28344. * @tsl
  28345. * @function
  28346. * @param {Node<vec2>} coord - The uv coordinates.
  28347. * @return {Node<float>} The result data.
  28348. */
  28349. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  28350. const uv = coord.mul( 2.0 );
  28351. const cx = uv.x.floor();
  28352. const cy = uv.y.floor();
  28353. const result = cx.add( cy ).mod( 2.0 );
  28354. return result.sign();
  28355. } );
  28356. /**
  28357. * Generates a circle based on the uv coordinates.
  28358. *
  28359. * @tsl
  28360. * @function
  28361. * @param {Node<vec2>} coord - The uv to generate the circle.
  28362. * @return {Node<float>} The circle shape.
  28363. */
  28364. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  28365. const alpha = float( 1 ).toVar();
  28366. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  28367. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  28368. const dlen = float( len2.fwidth() ).toVar();
  28369. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  28370. } else {
  28371. len2.greaterThan( 1.0 ).discard();
  28372. }
  28373. return alpha;
  28374. } );
  28375. // Three.js Transpiler
  28376. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  28377. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  28378. const f = float( f_immutable ).toVar();
  28379. const t = float( t_immutable ).toVar();
  28380. const b = bool( b_immutable ).toVar();
  28381. return select( b, t, f );
  28382. } ).setLayout( {
  28383. name: 'mx_select',
  28384. type: 'float',
  28385. inputs: [
  28386. { name: 'b', type: 'bool' },
  28387. { name: 't', type: 'float' },
  28388. { name: 'f', type: 'float' }
  28389. ]
  28390. } );
  28391. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  28392. const b = bool( b_immutable ).toVar();
  28393. const val = float( val_immutable ).toVar();
  28394. return select( b, val.negate(), val );
  28395. } ).setLayout( {
  28396. name: 'mx_negate_if',
  28397. type: 'float',
  28398. inputs: [
  28399. { name: 'val', type: 'float' },
  28400. { name: 'b', type: 'bool' }
  28401. ]
  28402. } );
  28403. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28404. const x = float( x_immutable ).toVar();
  28405. return int( floor( x ) );
  28406. } ).setLayout( {
  28407. name: 'mx_floor',
  28408. type: 'int',
  28409. inputs: [
  28410. { name: 'x', type: 'float' }
  28411. ]
  28412. } );
  28413. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  28414. const x = float( x_immutable ).toVar();
  28415. i.assign( mx_floor( x ) );
  28416. return x.sub( float( i ) );
  28417. } );
  28418. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28419. const t = float( t_immutable ).toVar();
  28420. const s = float( s_immutable ).toVar();
  28421. const v3 = float( v3_immutable ).toVar();
  28422. const v2 = float( v2_immutable ).toVar();
  28423. const v1 = float( v1_immutable ).toVar();
  28424. const v0 = float( v0_immutable ).toVar();
  28425. const s1 = float( sub( 1.0, s ) ).toVar();
  28426. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28427. } ).setLayout( {
  28428. name: 'mx_bilerp_0',
  28429. type: 'float',
  28430. inputs: [
  28431. { name: 'v0', type: 'float' },
  28432. { name: 'v1', type: 'float' },
  28433. { name: 'v2', type: 'float' },
  28434. { name: 'v3', type: 'float' },
  28435. { name: 's', type: 'float' },
  28436. { name: 't', type: 'float' }
  28437. ]
  28438. } );
  28439. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28440. const t = float( t_immutable ).toVar();
  28441. const s = float( s_immutable ).toVar();
  28442. const v3 = vec3( v3_immutable ).toVar();
  28443. const v2 = vec3( v2_immutable ).toVar();
  28444. const v1 = vec3( v1_immutable ).toVar();
  28445. const v0 = vec3( v0_immutable ).toVar();
  28446. const s1 = float( sub( 1.0, s ) ).toVar();
  28447. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28448. } ).setLayout( {
  28449. name: 'mx_bilerp_1',
  28450. type: 'vec3',
  28451. inputs: [
  28452. { name: 'v0', type: 'vec3' },
  28453. { name: 'v1', type: 'vec3' },
  28454. { name: 'v2', type: 'vec3' },
  28455. { name: 'v3', type: 'vec3' },
  28456. { name: 's', type: 'float' },
  28457. { name: 't', type: 'float' }
  28458. ]
  28459. } );
  28460. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  28461. 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 ] ) => {
  28462. const r = float( r_immutable ).toVar();
  28463. const t = float( t_immutable ).toVar();
  28464. const s = float( s_immutable ).toVar();
  28465. const v7 = float( v7_immutable ).toVar();
  28466. const v6 = float( v6_immutable ).toVar();
  28467. const v5 = float( v5_immutable ).toVar();
  28468. const v4 = float( v4_immutable ).toVar();
  28469. const v3 = float( v3_immutable ).toVar();
  28470. const v2 = float( v2_immutable ).toVar();
  28471. const v1 = float( v1_immutable ).toVar();
  28472. const v0 = float( v0_immutable ).toVar();
  28473. const s1 = float( sub( 1.0, s ) ).toVar();
  28474. const t1 = float( sub( 1.0, t ) ).toVar();
  28475. const r1 = float( sub( 1.0, r ) ).toVar();
  28476. 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 ) ) ) ) ) );
  28477. } ).setLayout( {
  28478. name: 'mx_trilerp_0',
  28479. type: 'float',
  28480. inputs: [
  28481. { name: 'v0', type: 'float' },
  28482. { name: 'v1', type: 'float' },
  28483. { name: 'v2', type: 'float' },
  28484. { name: 'v3', type: 'float' },
  28485. { name: 'v4', type: 'float' },
  28486. { name: 'v5', type: 'float' },
  28487. { name: 'v6', type: 'float' },
  28488. { name: 'v7', type: 'float' },
  28489. { name: 's', type: 'float' },
  28490. { name: 't', type: 'float' },
  28491. { name: 'r', type: 'float' }
  28492. ]
  28493. } );
  28494. 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 ] ) => {
  28495. const r = float( r_immutable ).toVar();
  28496. const t = float( t_immutable ).toVar();
  28497. const s = float( s_immutable ).toVar();
  28498. const v7 = vec3( v7_immutable ).toVar();
  28499. const v6 = vec3( v6_immutable ).toVar();
  28500. const v5 = vec3( v5_immutable ).toVar();
  28501. const v4 = vec3( v4_immutable ).toVar();
  28502. const v3 = vec3( v3_immutable ).toVar();
  28503. const v2 = vec3( v2_immutable ).toVar();
  28504. const v1 = vec3( v1_immutable ).toVar();
  28505. const v0 = vec3( v0_immutable ).toVar();
  28506. const s1 = float( sub( 1.0, s ) ).toVar();
  28507. const t1 = float( sub( 1.0, t ) ).toVar();
  28508. const r1 = float( sub( 1.0, r ) ).toVar();
  28509. 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 ) ) ) ) ) );
  28510. } ).setLayout( {
  28511. name: 'mx_trilerp_1',
  28512. type: 'vec3',
  28513. inputs: [
  28514. { name: 'v0', type: 'vec3' },
  28515. { name: 'v1', type: 'vec3' },
  28516. { name: 'v2', type: 'vec3' },
  28517. { name: 'v3', type: 'vec3' },
  28518. { name: 'v4', type: 'vec3' },
  28519. { name: 'v5', type: 'vec3' },
  28520. { name: 'v6', type: 'vec3' },
  28521. { name: 'v7', type: 'vec3' },
  28522. { name: 's', type: 'float' },
  28523. { name: 't', type: 'float' },
  28524. { name: 'r', type: 'float' }
  28525. ]
  28526. } );
  28527. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  28528. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28529. const y = float( y_immutable ).toVar();
  28530. const x = float( x_immutable ).toVar();
  28531. const hash = uint( hash_immutable ).toVar();
  28532. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  28533. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  28534. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  28535. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28536. } ).setLayout( {
  28537. name: 'mx_gradient_float_0',
  28538. type: 'float',
  28539. inputs: [
  28540. { name: 'hash', type: 'uint' },
  28541. { name: 'x', type: 'float' },
  28542. { name: 'y', type: 'float' }
  28543. ]
  28544. } );
  28545. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28546. const z = float( z_immutable ).toVar();
  28547. const y = float( y_immutable ).toVar();
  28548. const x = float( x_immutable ).toVar();
  28549. const hash = uint( hash_immutable ).toVar();
  28550. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  28551. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  28552. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  28553. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28554. } ).setLayout( {
  28555. name: 'mx_gradient_float_1',
  28556. type: 'float',
  28557. inputs: [
  28558. { name: 'hash', type: 'uint' },
  28559. { name: 'x', type: 'float' },
  28560. { name: 'y', type: 'float' },
  28561. { name: 'z', type: 'float' }
  28562. ]
  28563. } );
  28564. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  28565. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28566. const y = float( y_immutable ).toVar();
  28567. const x = float( x_immutable ).toVar();
  28568. const hash = uvec3( hash_immutable ).toVar();
  28569. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  28570. } ).setLayout( {
  28571. name: 'mx_gradient_vec3_0',
  28572. type: 'vec3',
  28573. inputs: [
  28574. { name: 'hash', type: 'uvec3' },
  28575. { name: 'x', type: 'float' },
  28576. { name: 'y', type: 'float' }
  28577. ]
  28578. } );
  28579. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28580. const z = float( z_immutable ).toVar();
  28581. const y = float( y_immutable ).toVar();
  28582. const x = float( x_immutable ).toVar();
  28583. const hash = uvec3( hash_immutable ).toVar();
  28584. 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 ) );
  28585. } ).setLayout( {
  28586. name: 'mx_gradient_vec3_1',
  28587. type: 'vec3',
  28588. inputs: [
  28589. { name: 'hash', type: 'uvec3' },
  28590. { name: 'x', type: 'float' },
  28591. { name: 'y', type: 'float' },
  28592. { name: 'z', type: 'float' }
  28593. ]
  28594. } );
  28595. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  28596. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28597. const v = float( v_immutable ).toVar();
  28598. return mul( 0.6616, v );
  28599. } ).setLayout( {
  28600. name: 'mx_gradient_scale2d_0',
  28601. type: 'float',
  28602. inputs: [
  28603. { name: 'v', type: 'float' }
  28604. ]
  28605. } );
  28606. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28607. const v = float( v_immutable ).toVar();
  28608. return mul( 0.9820, v );
  28609. } ).setLayout( {
  28610. name: 'mx_gradient_scale3d_0',
  28611. type: 'float',
  28612. inputs: [
  28613. { name: 'v', type: 'float' }
  28614. ]
  28615. } );
  28616. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28617. const v = vec3( v_immutable ).toVar();
  28618. return mul( 0.6616, v );
  28619. } ).setLayout( {
  28620. name: 'mx_gradient_scale2d_1',
  28621. type: 'vec3',
  28622. inputs: [
  28623. { name: 'v', type: 'vec3' }
  28624. ]
  28625. } );
  28626. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  28627. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28628. const v = vec3( v_immutable ).toVar();
  28629. return mul( 0.9820, v );
  28630. } ).setLayout( {
  28631. name: 'mx_gradient_scale3d_1',
  28632. type: 'vec3',
  28633. inputs: [
  28634. { name: 'v', type: 'vec3' }
  28635. ]
  28636. } );
  28637. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  28638. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  28639. const k = int( k_immutable ).toVar();
  28640. const x = uint( x_immutable ).toVar();
  28641. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  28642. } ).setLayout( {
  28643. name: 'mx_rotl32',
  28644. type: 'uint',
  28645. inputs: [
  28646. { name: 'x', type: 'uint' },
  28647. { name: 'k', type: 'int' }
  28648. ]
  28649. } );
  28650. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  28651. a.subAssign( c );
  28652. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  28653. c.addAssign( b );
  28654. b.subAssign( a );
  28655. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  28656. a.addAssign( c );
  28657. c.subAssign( b );
  28658. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  28659. b.addAssign( a );
  28660. a.subAssign( c );
  28661. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  28662. c.addAssign( b );
  28663. b.subAssign( a );
  28664. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  28665. a.addAssign( c );
  28666. c.subAssign( b );
  28667. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  28668. b.addAssign( a );
  28669. } );
  28670. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  28671. const c = uint( c_immutable ).toVar();
  28672. const b = uint( b_immutable ).toVar();
  28673. const a = uint( a_immutable ).toVar();
  28674. c.bitXorAssign( b );
  28675. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  28676. a.bitXorAssign( c );
  28677. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  28678. b.bitXorAssign( a );
  28679. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  28680. c.bitXorAssign( b );
  28681. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  28682. a.bitXorAssign( c );
  28683. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  28684. b.bitXorAssign( a );
  28685. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  28686. c.bitXorAssign( b );
  28687. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  28688. return c;
  28689. } ).setLayout( {
  28690. name: 'mx_bjfinal',
  28691. type: 'uint',
  28692. inputs: [
  28693. { name: 'a', type: 'uint' },
  28694. { name: 'b', type: 'uint' },
  28695. { name: 'c', type: 'uint' }
  28696. ]
  28697. } );
  28698. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  28699. const bits = uint( bits_immutable ).toVar();
  28700. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  28701. } ).setLayout( {
  28702. name: 'mx_bits_to_01',
  28703. type: 'float',
  28704. inputs: [
  28705. { name: 'bits', type: 'uint' }
  28706. ]
  28707. } );
  28708. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  28709. const t = float( t_immutable ).toVar();
  28710. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  28711. } ).setLayout( {
  28712. name: 'mx_fade',
  28713. type: 'float',
  28714. inputs: [
  28715. { name: 't', type: 'float' }
  28716. ]
  28717. } );
  28718. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28719. const x = int( x_immutable ).toVar();
  28720. const len = uint( uint( 1 ) ).toVar();
  28721. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  28722. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  28723. } ).setLayout( {
  28724. name: 'mx_hash_int_0',
  28725. type: 'uint',
  28726. inputs: [
  28727. { name: 'x', type: 'int' }
  28728. ]
  28729. } );
  28730. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28731. const y = int( y_immutable ).toVar();
  28732. const x = int( x_immutable ).toVar();
  28733. const len = uint( uint( 2 ) ).toVar();
  28734. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28735. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28736. a.addAssign( uint( x ) );
  28737. b.addAssign( uint( y ) );
  28738. return mx_bjfinal( a, b, c );
  28739. } ).setLayout( {
  28740. name: 'mx_hash_int_1',
  28741. type: 'uint',
  28742. inputs: [
  28743. { name: 'x', type: 'int' },
  28744. { name: 'y', type: 'int' }
  28745. ]
  28746. } );
  28747. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28748. const z = int( z_immutable ).toVar();
  28749. const y = int( y_immutable ).toVar();
  28750. const x = int( x_immutable ).toVar();
  28751. const len = uint( uint( 3 ) ).toVar();
  28752. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28753. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28754. a.addAssign( uint( x ) );
  28755. b.addAssign( uint( y ) );
  28756. c.addAssign( uint( z ) );
  28757. return mx_bjfinal( a, b, c );
  28758. } ).setLayout( {
  28759. name: 'mx_hash_int_2',
  28760. type: 'uint',
  28761. inputs: [
  28762. { name: 'x', type: 'int' },
  28763. { name: 'y', type: 'int' },
  28764. { name: 'z', type: 'int' }
  28765. ]
  28766. } );
  28767. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  28768. const xx = int( xx_immutable ).toVar();
  28769. const z = int( z_immutable ).toVar();
  28770. const y = int( y_immutable ).toVar();
  28771. const x = int( x_immutable ).toVar();
  28772. const len = uint( uint( 4 ) ).toVar();
  28773. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28774. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28775. a.addAssign( uint( x ) );
  28776. b.addAssign( uint( y ) );
  28777. c.addAssign( uint( z ) );
  28778. mx_bjmix( a, b, c );
  28779. a.addAssign( uint( xx ) );
  28780. return mx_bjfinal( a, b, c );
  28781. } ).setLayout( {
  28782. name: 'mx_hash_int_3',
  28783. type: 'uint',
  28784. inputs: [
  28785. { name: 'x', type: 'int' },
  28786. { name: 'y', type: 'int' },
  28787. { name: 'z', type: 'int' },
  28788. { name: 'xx', type: 'int' }
  28789. ]
  28790. } );
  28791. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  28792. const yy = int( yy_immutable ).toVar();
  28793. const xx = int( xx_immutable ).toVar();
  28794. const z = int( z_immutable ).toVar();
  28795. const y = int( y_immutable ).toVar();
  28796. const x = int( x_immutable ).toVar();
  28797. const len = uint( uint( 5 ) ).toVar();
  28798. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  28799. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  28800. a.addAssign( uint( x ) );
  28801. b.addAssign( uint( y ) );
  28802. c.addAssign( uint( z ) );
  28803. mx_bjmix( a, b, c );
  28804. a.addAssign( uint( xx ) );
  28805. b.addAssign( uint( yy ) );
  28806. return mx_bjfinal( a, b, c );
  28807. } ).setLayout( {
  28808. name: 'mx_hash_int_4',
  28809. type: 'uint',
  28810. inputs: [
  28811. { name: 'x', type: 'int' },
  28812. { name: 'y', type: 'int' },
  28813. { name: 'z', type: 'int' },
  28814. { name: 'xx', type: 'int' },
  28815. { name: 'yy', type: 'int' }
  28816. ]
  28817. } );
  28818. 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 ] );
  28819. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  28820. const y = int( y_immutable ).toVar();
  28821. const x = int( x_immutable ).toVar();
  28822. const h = uint( mx_hash_int( x, y ) ).toVar();
  28823. const result = uvec3().toVar();
  28824. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  28825. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  28826. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  28827. return result;
  28828. } ).setLayout( {
  28829. name: 'mx_hash_vec3_0',
  28830. type: 'uvec3',
  28831. inputs: [
  28832. { name: 'x', type: 'int' },
  28833. { name: 'y', type: 'int' }
  28834. ]
  28835. } );
  28836. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  28837. const z = int( z_immutable ).toVar();
  28838. const y = int( y_immutable ).toVar();
  28839. const x = int( x_immutable ).toVar();
  28840. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  28841. const result = uvec3().toVar();
  28842. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  28843. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  28844. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  28845. return result;
  28846. } ).setLayout( {
  28847. name: 'mx_hash_vec3_1',
  28848. type: 'uvec3',
  28849. inputs: [
  28850. { name: 'x', type: 'int' },
  28851. { name: 'y', type: 'int' },
  28852. { name: 'z', type: 'int' }
  28853. ]
  28854. } );
  28855. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  28856. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28857. const p = vec2( p_immutable ).toVar();
  28858. const X = int().toVar(), Y = int().toVar();
  28859. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28860. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28861. const u = float( mx_fade( fx ) ).toVar();
  28862. const v = float( mx_fade( fy ) ).toVar();
  28863. 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();
  28864. return mx_gradient_scale2d( result );
  28865. } ).setLayout( {
  28866. name: 'mx_perlin_noise_float_0',
  28867. type: 'float',
  28868. inputs: [
  28869. { name: 'p', type: 'vec2' }
  28870. ]
  28871. } );
  28872. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28873. const p = vec3( p_immutable ).toVar();
  28874. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28875. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28876. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28877. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  28878. const u = float( mx_fade( fx ) ).toVar();
  28879. const v = float( mx_fade( fy ) ).toVar();
  28880. const w = float( mx_fade( fz ) ).toVar();
  28881. 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();
  28882. return mx_gradient_scale3d( result );
  28883. } ).setLayout( {
  28884. name: 'mx_perlin_noise_float_1',
  28885. type: 'float',
  28886. inputs: [
  28887. { name: 'p', type: 'vec3' }
  28888. ]
  28889. } );
  28890. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  28891. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28892. const p = vec2( p_immutable ).toVar();
  28893. const X = int().toVar(), Y = int().toVar();
  28894. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28895. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28896. const u = float( mx_fade( fx ) ).toVar();
  28897. const v = float( mx_fade( fy ) ).toVar();
  28898. 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();
  28899. return mx_gradient_scale2d( result );
  28900. } ).setLayout( {
  28901. name: 'mx_perlin_noise_vec3_0',
  28902. type: 'vec3',
  28903. inputs: [
  28904. { name: 'p', type: 'vec2' }
  28905. ]
  28906. } );
  28907. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28908. const p = vec3( p_immutable ).toVar();
  28909. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  28910. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  28911. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  28912. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  28913. const u = float( mx_fade( fx ) ).toVar();
  28914. const v = float( mx_fade( fy ) ).toVar();
  28915. const w = float( mx_fade( fz ) ).toVar();
  28916. 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();
  28917. return mx_gradient_scale3d( result );
  28918. } ).setLayout( {
  28919. name: 'mx_perlin_noise_vec3_1',
  28920. type: 'vec3',
  28921. inputs: [
  28922. { name: 'p', type: 'vec3' }
  28923. ]
  28924. } );
  28925. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  28926. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28927. const p = float( p_immutable ).toVar();
  28928. const ix = int( mx_floor( p ) ).toVar();
  28929. return mx_bits_to_01( mx_hash_int( ix ) );
  28930. } ).setLayout( {
  28931. name: 'mx_cell_noise_float_0',
  28932. type: 'float',
  28933. inputs: [
  28934. { name: 'p', type: 'float' }
  28935. ]
  28936. } );
  28937. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28938. const p = vec2( p_immutable ).toVar();
  28939. const ix = int( mx_floor( p.x ) ).toVar();
  28940. const iy = int( mx_floor( p.y ) ).toVar();
  28941. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  28942. } ).setLayout( {
  28943. name: 'mx_cell_noise_float_1',
  28944. type: 'float',
  28945. inputs: [
  28946. { name: 'p', type: 'vec2' }
  28947. ]
  28948. } );
  28949. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28950. const p = vec3( p_immutable ).toVar();
  28951. const ix = int( mx_floor( p.x ) ).toVar();
  28952. const iy = int( mx_floor( p.y ) ).toVar();
  28953. const iz = int( mx_floor( p.z ) ).toVar();
  28954. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  28955. } ).setLayout( {
  28956. name: 'mx_cell_noise_float_2',
  28957. type: 'float',
  28958. inputs: [
  28959. { name: 'p', type: 'vec3' }
  28960. ]
  28961. } );
  28962. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28963. const p = vec4( p_immutable ).toVar();
  28964. const ix = int( mx_floor( p.x ) ).toVar();
  28965. const iy = int( mx_floor( p.y ) ).toVar();
  28966. const iz = int( mx_floor( p.z ) ).toVar();
  28967. const iw = int( mx_floor( p.w ) ).toVar();
  28968. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  28969. } ).setLayout( {
  28970. name: 'mx_cell_noise_float_3',
  28971. type: 'float',
  28972. inputs: [
  28973. { name: 'p', type: 'vec4' }
  28974. ]
  28975. } );
  28976. 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 ] );
  28977. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28978. const p = float( p_immutable ).toVar();
  28979. const ix = int( mx_floor( p ) ).toVar();
  28980. 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 ) ) ) );
  28981. } ).setLayout( {
  28982. name: 'mx_cell_noise_vec3_0',
  28983. type: 'vec3',
  28984. inputs: [
  28985. { name: 'p', type: 'float' }
  28986. ]
  28987. } );
  28988. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  28989. const p = vec2( p_immutable ).toVar();
  28990. const ix = int( mx_floor( p.x ) ).toVar();
  28991. const iy = int( mx_floor( p.y ) ).toVar();
  28992. 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 ) ) ) );
  28993. } ).setLayout( {
  28994. name: 'mx_cell_noise_vec3_1',
  28995. type: 'vec3',
  28996. inputs: [
  28997. { name: 'p', type: 'vec2' }
  28998. ]
  28999. } );
  29000. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29001. const p = vec3( p_immutable ).toVar();
  29002. const ix = int( mx_floor( p.x ) ).toVar();
  29003. const iy = int( mx_floor( p.y ) ).toVar();
  29004. const iz = int( mx_floor( p.z ) ).toVar();
  29005. 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 ) ) ) );
  29006. } ).setLayout( {
  29007. name: 'mx_cell_noise_vec3_2',
  29008. type: 'vec3',
  29009. inputs: [
  29010. { name: 'p', type: 'vec3' }
  29011. ]
  29012. } );
  29013. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29014. const p = vec4( p_immutable ).toVar();
  29015. const ix = int( mx_floor( p.x ) ).toVar();
  29016. const iy = int( mx_floor( p.y ) ).toVar();
  29017. const iz = int( mx_floor( p.z ) ).toVar();
  29018. const iw = int( mx_floor( p.w ) ).toVar();
  29019. 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 ) ) ) );
  29020. } ).setLayout( {
  29021. name: 'mx_cell_noise_vec3_3',
  29022. type: 'vec3',
  29023. inputs: [
  29024. { name: 'p', type: 'vec4' }
  29025. ]
  29026. } );
  29027. 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 ] );
  29028. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29029. const diminish = float( diminish_immutable ).toVar();
  29030. const lacunarity = float( lacunarity_immutable ).toVar();
  29031. const octaves = int( octaves_immutable ).toVar();
  29032. const p = vec3( p_immutable ).toVar();
  29033. const result = float( 0.0 ).toVar();
  29034. const amplitude = float( 1.0 ).toVar();
  29035. Loop( octaves, () => {
  29036. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  29037. amplitude.mulAssign( diminish );
  29038. p.mulAssign( lacunarity );
  29039. } );
  29040. return result;
  29041. } ).setLayout( {
  29042. name: 'mx_fractal_noise_float',
  29043. type: 'float',
  29044. inputs: [
  29045. { name: 'p', type: 'vec3' },
  29046. { name: 'octaves', type: 'int' },
  29047. { name: 'lacunarity', type: 'float' },
  29048. { name: 'diminish', type: 'float' }
  29049. ]
  29050. } );
  29051. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29052. const diminish = float( diminish_immutable ).toVar();
  29053. const lacunarity = float( lacunarity_immutable ).toVar();
  29054. const octaves = int( octaves_immutable ).toVar();
  29055. const p = vec3( p_immutable ).toVar();
  29056. const result = vec3( 0.0 ).toVar();
  29057. const amplitude = float( 1.0 ).toVar();
  29058. Loop( octaves, () => {
  29059. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  29060. amplitude.mulAssign( diminish );
  29061. p.mulAssign( lacunarity );
  29062. } );
  29063. return result;
  29064. } ).setLayout( {
  29065. name: 'mx_fractal_noise_vec3',
  29066. type: 'vec3',
  29067. inputs: [
  29068. { name: 'p', type: 'vec3' },
  29069. { name: 'octaves', type: 'int' },
  29070. { name: 'lacunarity', type: 'float' },
  29071. { name: 'diminish', type: 'float' }
  29072. ]
  29073. } );
  29074. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29075. const diminish = float( diminish_immutable ).toVar();
  29076. const lacunarity = float( lacunarity_immutable ).toVar();
  29077. const octaves = int( octaves_immutable ).toVar();
  29078. const p = vec3( p_immutable ).toVar();
  29079. 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 ) );
  29080. } ).setLayout( {
  29081. name: 'mx_fractal_noise_vec2',
  29082. type: 'vec2',
  29083. inputs: [
  29084. { name: 'p', type: 'vec3' },
  29085. { name: 'octaves', type: 'int' },
  29086. { name: 'lacunarity', type: 'float' },
  29087. { name: 'diminish', type: 'float' }
  29088. ]
  29089. } );
  29090. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29091. const diminish = float( diminish_immutable ).toVar();
  29092. const lacunarity = float( lacunarity_immutable ).toVar();
  29093. const octaves = int( octaves_immutable ).toVar();
  29094. const p = vec3( p_immutable ).toVar();
  29095. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  29096. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  29097. return vec4( c, f );
  29098. } ).setLayout( {
  29099. name: 'mx_fractal_noise_vec4',
  29100. type: 'vec4',
  29101. inputs: [
  29102. { name: 'p', type: 'vec3' },
  29103. { name: 'octaves', type: 'int' },
  29104. { name: 'lacunarity', type: 'float' },
  29105. { name: 'diminish', type: 'float' }
  29106. ]
  29107. } );
  29108. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  29109. const metric = int( metric_immutable ).toVar();
  29110. const jitter = float( jitter_immutable ).toVar();
  29111. const yoff = int( yoff_immutable ).toVar();
  29112. const xoff = int( xoff_immutable ).toVar();
  29113. const y = int( y_immutable ).toVar();
  29114. const x = int( x_immutable ).toVar();
  29115. const p = vec2( p_immutable ).toVar();
  29116. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  29117. const off = vec2( tmp.x, tmp.y ).toVar();
  29118. off.subAssign( 0.5 );
  29119. off.mulAssign( jitter );
  29120. off.addAssign( 0.5 );
  29121. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  29122. const diff = vec2( cellpos.sub( p ) ).toVar();
  29123. If( metric.equal( int( 2 ) ), () => {
  29124. return abs( diff.x ).add( abs( diff.y ) );
  29125. } );
  29126. If( metric.equal( int( 3 ) ), () => {
  29127. return max$1( abs( diff.x ), abs( diff.y ) );
  29128. } );
  29129. return dot( diff, diff );
  29130. } ).setLayout( {
  29131. name: 'mx_worley_distance_0',
  29132. type: 'float',
  29133. inputs: [
  29134. { name: 'p', type: 'vec2' },
  29135. { name: 'x', type: 'int' },
  29136. { name: 'y', type: 'int' },
  29137. { name: 'xoff', type: 'int' },
  29138. { name: 'yoff', type: 'int' },
  29139. { name: 'jitter', type: 'float' },
  29140. { name: 'metric', type: 'int' }
  29141. ]
  29142. } );
  29143. 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 ] ) => {
  29144. const metric = int( metric_immutable ).toVar();
  29145. const jitter = float( jitter_immutable ).toVar();
  29146. const zoff = int( zoff_immutable ).toVar();
  29147. const yoff = int( yoff_immutable ).toVar();
  29148. const xoff = int( xoff_immutable ).toVar();
  29149. const z = int( z_immutable ).toVar();
  29150. const y = int( y_immutable ).toVar();
  29151. const x = int( x_immutable ).toVar();
  29152. const p = vec3( p_immutable ).toVar();
  29153. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  29154. off.subAssign( 0.5 );
  29155. off.mulAssign( jitter );
  29156. off.addAssign( 0.5 );
  29157. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  29158. const diff = vec3( cellpos.sub( p ) ).toVar();
  29159. If( metric.equal( int( 2 ) ), () => {
  29160. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  29161. } );
  29162. If( metric.equal( int( 3 ) ), () => {
  29163. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  29164. } );
  29165. return dot( diff, diff );
  29166. } ).setLayout( {
  29167. name: 'mx_worley_distance_1',
  29168. type: 'float',
  29169. inputs: [
  29170. { name: 'p', type: 'vec3' },
  29171. { name: 'x', type: 'int' },
  29172. { name: 'y', type: 'int' },
  29173. { name: 'z', type: 'int' },
  29174. { name: 'xoff', type: 'int' },
  29175. { name: 'yoff', type: 'int' },
  29176. { name: 'zoff', type: 'int' },
  29177. { name: 'jitter', type: 'float' },
  29178. { name: 'metric', type: 'int' }
  29179. ]
  29180. } );
  29181. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  29182. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29183. const metric = int( metric_immutable ).toVar();
  29184. const jitter = float( jitter_immutable ).toVar();
  29185. const p = vec2( p_immutable ).toVar();
  29186. const X = int().toVar(), Y = int().toVar();
  29187. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29188. const sqdist = float( 1e6 ).toVar();
  29189. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29190. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29191. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29192. sqdist.assign( min$1( sqdist, dist ) );
  29193. } );
  29194. } );
  29195. If( metric.equal( int( 0 ) ), () => {
  29196. sqdist.assign( sqrt( sqdist ) );
  29197. } );
  29198. return sqdist;
  29199. } ).setLayout( {
  29200. name: 'mx_worley_noise_float_0',
  29201. type: 'float',
  29202. inputs: [
  29203. { name: 'p', type: 'vec2' },
  29204. { name: 'jitter', type: 'float' },
  29205. { name: 'metric', type: 'int' }
  29206. ]
  29207. } );
  29208. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29209. const metric = int( metric_immutable ).toVar();
  29210. const jitter = float( jitter_immutable ).toVar();
  29211. const p = vec2( p_immutable ).toVar();
  29212. const X = int().toVar(), Y = int().toVar();
  29213. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29214. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29215. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29216. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29217. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29218. If( dist.lessThan( sqdist.x ), () => {
  29219. sqdist.y.assign( sqdist.x );
  29220. sqdist.x.assign( dist );
  29221. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29222. sqdist.y.assign( dist );
  29223. } );
  29224. } );
  29225. } );
  29226. If( metric.equal( int( 0 ) ), () => {
  29227. sqdist.assign( sqrt( sqdist ) );
  29228. } );
  29229. return sqdist;
  29230. } ).setLayout( {
  29231. name: 'mx_worley_noise_vec2_0',
  29232. type: 'vec2',
  29233. inputs: [
  29234. { name: 'p', type: 'vec2' },
  29235. { name: 'jitter', type: 'float' },
  29236. { name: 'metric', type: 'int' }
  29237. ]
  29238. } );
  29239. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29240. const metric = int( metric_immutable ).toVar();
  29241. const jitter = float( jitter_immutable ).toVar();
  29242. const p = vec2( p_immutable ).toVar();
  29243. const X = int().toVar(), Y = int().toVar();
  29244. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29245. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29246. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29247. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29248. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29249. If( dist.lessThan( sqdist.x ), () => {
  29250. sqdist.z.assign( sqdist.y );
  29251. sqdist.y.assign( sqdist.x );
  29252. sqdist.x.assign( dist );
  29253. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29254. sqdist.z.assign( sqdist.y );
  29255. sqdist.y.assign( dist );
  29256. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29257. sqdist.z.assign( dist );
  29258. } );
  29259. } );
  29260. } );
  29261. If( metric.equal( int( 0 ) ), () => {
  29262. sqdist.assign( sqrt( sqdist ) );
  29263. } );
  29264. return sqdist;
  29265. } ).setLayout( {
  29266. name: 'mx_worley_noise_vec3_0',
  29267. type: 'vec3',
  29268. inputs: [
  29269. { name: 'p', type: 'vec2' },
  29270. { name: 'jitter', type: 'float' },
  29271. { name: 'metric', type: 'int' }
  29272. ]
  29273. } );
  29274. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29275. const metric = int( metric_immutable ).toVar();
  29276. const jitter = float( jitter_immutable ).toVar();
  29277. const p = vec3( p_immutable ).toVar();
  29278. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29279. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29280. const sqdist = float( 1e6 ).toVar();
  29281. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29282. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29283. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29284. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29285. sqdist.assign( min$1( sqdist, dist ) );
  29286. } );
  29287. } );
  29288. } );
  29289. If( metric.equal( int( 0 ) ), () => {
  29290. sqdist.assign( sqrt( sqdist ) );
  29291. } );
  29292. return sqdist;
  29293. } ).setLayout( {
  29294. name: 'mx_worley_noise_float_1',
  29295. type: 'float',
  29296. inputs: [
  29297. { name: 'p', type: 'vec3' },
  29298. { name: 'jitter', type: 'float' },
  29299. { name: 'metric', type: 'int' }
  29300. ]
  29301. } );
  29302. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  29303. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29304. const metric = int( metric_immutable ).toVar();
  29305. const jitter = float( jitter_immutable ).toVar();
  29306. const p = vec3( p_immutable ).toVar();
  29307. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29308. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29309. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29310. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29311. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29312. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29313. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29314. If( dist.lessThan( sqdist.x ), () => {
  29315. sqdist.y.assign( sqdist.x );
  29316. sqdist.x.assign( dist );
  29317. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29318. sqdist.y.assign( dist );
  29319. } );
  29320. } );
  29321. } );
  29322. } );
  29323. If( metric.equal( int( 0 ) ), () => {
  29324. sqdist.assign( sqrt( sqdist ) );
  29325. } );
  29326. return sqdist;
  29327. } ).setLayout( {
  29328. name: 'mx_worley_noise_vec2_1',
  29329. type: 'vec2',
  29330. inputs: [
  29331. { name: 'p', type: 'vec3' },
  29332. { name: 'jitter', type: 'float' },
  29333. { name: 'metric', type: 'int' }
  29334. ]
  29335. } );
  29336. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  29337. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29338. const metric = int( metric_immutable ).toVar();
  29339. const jitter = float( jitter_immutable ).toVar();
  29340. const p = vec3( p_immutable ).toVar();
  29341. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29342. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29343. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29344. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29345. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29346. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29347. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29348. If( dist.lessThan( sqdist.x ), () => {
  29349. sqdist.z.assign( sqdist.y );
  29350. sqdist.y.assign( sqdist.x );
  29351. sqdist.x.assign( dist );
  29352. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29353. sqdist.z.assign( sqdist.y );
  29354. sqdist.y.assign( dist );
  29355. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29356. sqdist.z.assign( dist );
  29357. } );
  29358. } );
  29359. } );
  29360. } );
  29361. If( metric.equal( int( 0 ) ), () => {
  29362. sqdist.assign( sqrt( sqdist ) );
  29363. } );
  29364. return sqdist;
  29365. } ).setLayout( {
  29366. name: 'mx_worley_noise_vec3_1',
  29367. type: 'vec3',
  29368. inputs: [
  29369. { name: 'p', type: 'vec3' },
  29370. { name: 'jitter', type: 'float' },
  29371. { name: 'metric', type: 'int' }
  29372. ]
  29373. } );
  29374. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  29375. // Three.js Transpiler
  29376. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  29377. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  29378. const s = hsv.y;
  29379. const v = hsv.z;
  29380. const result = vec3().toVar();
  29381. If( s.lessThan( 0.0001 ), () => {
  29382. result.assign( vec3( v, v, v ) );
  29383. } ).Else( () => {
  29384. let h = hsv.x;
  29385. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  29386. const hi = int( trunc( h ) );
  29387. const f = h.sub( float( hi ) );
  29388. const p = v.mul( s.oneMinus() );
  29389. const q = v.mul( s.mul( f ).oneMinus() );
  29390. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  29391. If( hi.equal( int( 0 ) ), () => {
  29392. result.assign( vec3( v, t, p ) );
  29393. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  29394. result.assign( vec3( q, v, p ) );
  29395. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  29396. result.assign( vec3( p, v, t ) );
  29397. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  29398. result.assign( vec3( p, q, v ) );
  29399. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  29400. result.assign( vec3( t, p, v ) );
  29401. } ).Else( () => {
  29402. result.assign( vec3( v, p, q ) );
  29403. } );
  29404. } );
  29405. return result;
  29406. } ).setLayout( {
  29407. name: 'mx_hsvtorgb',
  29408. type: 'vec3',
  29409. inputs: [
  29410. { name: 'hsv', type: 'vec3' }
  29411. ]
  29412. } );
  29413. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  29414. const c = vec3( c_immutable ).toVar();
  29415. const r = float( c.x ).toVar();
  29416. const g = float( c.y ).toVar();
  29417. const b = float( c.z ).toVar();
  29418. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  29419. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  29420. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  29421. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  29422. v.assign( maxcomp );
  29423. If( maxcomp.greaterThan( 0.0 ), () => {
  29424. s.assign( delta.div( maxcomp ) );
  29425. } ).Else( () => {
  29426. s.assign( 0.0 );
  29427. } );
  29428. If( s.lessThanEqual( 0.0 ), () => {
  29429. h.assign( 0.0 );
  29430. } ).Else( () => {
  29431. If( r.greaterThanEqual( maxcomp ), () => {
  29432. h.assign( g.sub( b ).div( delta ) );
  29433. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  29434. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  29435. } ).Else( () => {
  29436. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  29437. } );
  29438. h.mulAssign( 1.0 / 6.0 );
  29439. If( h.lessThan( 0.0 ), () => {
  29440. h.addAssign( 1.0 );
  29441. } );
  29442. } );
  29443. return vec3( h, s, v );
  29444. } ).setLayout( {
  29445. name: 'mx_rgbtohsv',
  29446. type: 'vec3',
  29447. inputs: [
  29448. { name: 'c', type: 'vec3' }
  29449. ]
  29450. } );
  29451. // Three.js Transpiler
  29452. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  29453. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  29454. const color = vec3( color_immutable ).toVar();
  29455. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  29456. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  29457. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  29458. return mix( linSeg, powSeg, isAbove );
  29459. } ).setLayout( {
  29460. name: 'mx_srgb_texture_to_lin_rec709',
  29461. type: 'vec3',
  29462. inputs: [
  29463. { name: 'color', type: 'vec3' }
  29464. ]
  29465. } );
  29466. const mx_aastep = ( threshold, value ) => {
  29467. threshold = float( threshold );
  29468. value = float( value );
  29469. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  29470. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  29471. };
  29472. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  29473. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  29474. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  29475. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  29476. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  29477. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  29478. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  29479. const mx_safepower = ( in1, in2 = 1 ) => {
  29480. in1 = float( in1 );
  29481. return in1.abs().pow( in2 ).mul( in1.sign() );
  29482. };
  29483. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  29484. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29485. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29486. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29487. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  29488. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  29489. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  29490. return noise_vec4.mul( amplitude ).add( pivot );
  29491. };
  29492. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29493. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29494. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29495. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  29496. 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 );
  29497. 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 );
  29498. 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 );
  29499. 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 );
  29500. /**
  29501. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  29502. *
  29503. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  29504. *
  29505. * ```js
  29506. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  29507. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  29508. * ```
  29509. *
  29510. * @tsl
  29511. * @function
  29512. * @param {Node<vec3>} normal - The normal to correct.
  29513. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  29514. * @param {Node<vec3>} cubePos - The cube position.
  29515. * @return {Node<vec3>} The parallax corrected normal.
  29516. */
  29517. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  29518. const nDir = normalize( normal ).toVar();
  29519. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29520. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29521. const rbminmax = vec3().toVar();
  29522. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  29523. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  29524. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  29525. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar();
  29526. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  29527. return boxIntersection.sub( cubePos );
  29528. } );
  29529. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  29530. // normal is assumed to have unit length
  29531. const x = normal.x, y = normal.y, z = normal.z;
  29532. // band 0
  29533. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  29534. // band 1
  29535. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  29536. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  29537. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  29538. // band 2
  29539. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  29540. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  29541. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  29542. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  29543. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  29544. return result;
  29545. } );
  29546. // constants
  29547. var TSL = /*#__PURE__*/Object.freeze({
  29548. __proto__: null,
  29549. BRDF_GGX: BRDF_GGX,
  29550. BRDF_Lambert: BRDF_Lambert,
  29551. BasicPointShadowFilter: BasicPointShadowFilter,
  29552. BasicShadowFilter: BasicShadowFilter,
  29553. Break: Break,
  29554. Const: Const,
  29555. Continue: Continue,
  29556. DFGApprox: DFGApprox,
  29557. D_GGX: D_GGX,
  29558. Discard: Discard,
  29559. EPSILON: EPSILON,
  29560. F_Schlick: F_Schlick,
  29561. Fn: Fn,
  29562. INFINITY: INFINITY,
  29563. If: If,
  29564. Loop: Loop,
  29565. NodeAccess: NodeAccess,
  29566. NodeShaderStage: NodeShaderStage,
  29567. NodeType: NodeType,
  29568. NodeUpdateType: NodeUpdateType,
  29569. PCFShadowFilter: PCFShadowFilter,
  29570. PCFSoftShadowFilter: PCFSoftShadowFilter,
  29571. PI: PI,
  29572. PI2: PI2,
  29573. PointShadowFilter: PointShadowFilter,
  29574. Return: Return,
  29575. Schlick_to_F0: Schlick_to_F0,
  29576. ScriptableNodeResources: ScriptableNodeResources,
  29577. ShaderNode: ShaderNode,
  29578. Stack: Stack,
  29579. Switch: Switch,
  29580. TBNViewMatrix: TBNViewMatrix,
  29581. VSMShadowFilter: VSMShadowFilter,
  29582. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  29583. Var: Var,
  29584. abs: abs,
  29585. acesFilmicToneMapping: acesFilmicToneMapping,
  29586. acos: acos,
  29587. add: add,
  29588. addMethodChaining: addMethodChaining,
  29589. addNodeElement: addNodeElement,
  29590. agxToneMapping: agxToneMapping,
  29591. all: all,
  29592. alphaT: alphaT,
  29593. and: and,
  29594. anisotropy: anisotropy,
  29595. anisotropyB: anisotropyB,
  29596. anisotropyT: anisotropyT,
  29597. any: any,
  29598. append: append,
  29599. array: array,
  29600. arrayBuffer: arrayBuffer,
  29601. asin: asin,
  29602. assign: assign,
  29603. atan: atan,
  29604. atan2: atan2,
  29605. atomicAdd: atomicAdd,
  29606. atomicAnd: atomicAnd,
  29607. atomicFunc: atomicFunc,
  29608. atomicLoad: atomicLoad,
  29609. atomicMax: atomicMax,
  29610. atomicMin: atomicMin,
  29611. atomicOr: atomicOr,
  29612. atomicStore: atomicStore,
  29613. atomicSub: atomicSub,
  29614. atomicXor: atomicXor,
  29615. attenuationColor: attenuationColor,
  29616. attenuationDistance: attenuationDistance,
  29617. attribute: attribute,
  29618. attributeArray: attributeArray,
  29619. backgroundBlurriness: backgroundBlurriness,
  29620. backgroundIntensity: backgroundIntensity,
  29621. backgroundRotation: backgroundRotation,
  29622. batch: batch,
  29623. billboarding: billboarding,
  29624. bitAnd: bitAnd,
  29625. bitNot: bitNot,
  29626. bitOr: bitOr,
  29627. bitXor: bitXor,
  29628. bitangentGeometry: bitangentGeometry,
  29629. bitangentLocal: bitangentLocal,
  29630. bitangentView: bitangentView,
  29631. bitangentWorld: bitangentWorld,
  29632. bitcast: bitcast,
  29633. blendBurn: blendBurn,
  29634. blendColor: blendColor,
  29635. blendDodge: blendDodge,
  29636. blendOverlay: blendOverlay,
  29637. blendScreen: blendScreen,
  29638. blur: blur,
  29639. bool: bool,
  29640. buffer: buffer,
  29641. bufferAttribute: bufferAttribute,
  29642. bumpMap: bumpMap,
  29643. burn: burn,
  29644. bvec2: bvec2,
  29645. bvec3: bvec3,
  29646. bvec4: bvec4,
  29647. bypass: bypass,
  29648. cache: cache,
  29649. call: call,
  29650. cameraFar: cameraFar,
  29651. cameraIndex: cameraIndex,
  29652. cameraNear: cameraNear,
  29653. cameraNormalMatrix: cameraNormalMatrix,
  29654. cameraPosition: cameraPosition,
  29655. cameraProjectionMatrix: cameraProjectionMatrix,
  29656. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  29657. cameraViewMatrix: cameraViewMatrix,
  29658. cameraWorldMatrix: cameraWorldMatrix,
  29659. cbrt: cbrt,
  29660. cdl: cdl,
  29661. ceil: ceil,
  29662. checker: checker,
  29663. cineonToneMapping: cineonToneMapping,
  29664. clamp: clamp,
  29665. clearcoat: clearcoat,
  29666. clearcoatRoughness: clearcoatRoughness,
  29667. code: code,
  29668. color: color,
  29669. colorSpaceToWorking: colorSpaceToWorking,
  29670. colorToDirection: colorToDirection,
  29671. compute: compute,
  29672. computeSkinning: computeSkinning,
  29673. cond: cond,
  29674. context: context,
  29675. convert: convert,
  29676. convertColorSpace: convertColorSpace,
  29677. convertToTexture: convertToTexture,
  29678. cos: cos,
  29679. cross: cross,
  29680. cubeTexture: cubeTexture,
  29681. cubeToUV: cubeToUV,
  29682. dFdx: dFdx,
  29683. dFdy: dFdy,
  29684. dashSize: dashSize,
  29685. debug: debug,
  29686. decrement: decrement,
  29687. decrementBefore: decrementBefore,
  29688. defaultBuildStages: defaultBuildStages,
  29689. defaultShaderStages: defaultShaderStages,
  29690. defined: defined,
  29691. degrees: degrees,
  29692. deltaTime: deltaTime,
  29693. densityFog: densityFog,
  29694. densityFogFactor: densityFogFactor,
  29695. depth: depth,
  29696. depthPass: depthPass,
  29697. difference: difference,
  29698. diffuseColor: diffuseColor,
  29699. directPointLight: directPointLight,
  29700. directionToColor: directionToColor,
  29701. dispersion: dispersion,
  29702. distance: distance,
  29703. div: div,
  29704. dodge: dodge,
  29705. dot: dot,
  29706. drawIndex: drawIndex,
  29707. dynamicBufferAttribute: dynamicBufferAttribute,
  29708. element: element,
  29709. emissive: emissive,
  29710. equal: equal,
  29711. equals: equals,
  29712. equirectUV: equirectUV,
  29713. exp: exp,
  29714. exp2: exp2,
  29715. expression: expression,
  29716. faceDirection: faceDirection,
  29717. faceForward: faceForward,
  29718. faceforward: faceforward,
  29719. float: float,
  29720. floor: floor,
  29721. fog: fog,
  29722. fract: fract,
  29723. frameGroup: frameGroup,
  29724. frameId: frameId,
  29725. frontFacing: frontFacing,
  29726. fwidth: fwidth,
  29727. gain: gain,
  29728. gapSize: gapSize,
  29729. getConstNodeType: getConstNodeType,
  29730. getCurrentStack: getCurrentStack,
  29731. getDirection: getDirection,
  29732. getDistanceAttenuation: getDistanceAttenuation,
  29733. getGeometryRoughness: getGeometryRoughness,
  29734. getNormalFromDepth: getNormalFromDepth,
  29735. getParallaxCorrectNormal: getParallaxCorrectNormal,
  29736. getRoughness: getRoughness,
  29737. getScreenPosition: getScreenPosition,
  29738. getShIrradianceAt: getShIrradianceAt,
  29739. getShadowMaterial: getShadowMaterial,
  29740. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  29741. getTextureIndex: getTextureIndex,
  29742. getViewPosition: getViewPosition,
  29743. globalId: globalId,
  29744. glsl: glsl,
  29745. glslFn: glslFn,
  29746. grayscale: grayscale,
  29747. greaterThan: greaterThan,
  29748. greaterThanEqual: greaterThanEqual,
  29749. hash: hash,
  29750. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  29751. highpModelViewMatrix: highpModelViewMatrix,
  29752. hue: hue,
  29753. increment: increment,
  29754. incrementBefore: incrementBefore,
  29755. instance: instance,
  29756. instanceIndex: instanceIndex,
  29757. instancedArray: instancedArray,
  29758. instancedBufferAttribute: instancedBufferAttribute,
  29759. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  29760. instancedMesh: instancedMesh,
  29761. int: int,
  29762. inverseSqrt: inverseSqrt,
  29763. inversesqrt: inversesqrt,
  29764. invocationLocalIndex: invocationLocalIndex,
  29765. invocationSubgroupIndex: invocationSubgroupIndex,
  29766. ior: ior,
  29767. iridescence: iridescence,
  29768. iridescenceIOR: iridescenceIOR,
  29769. iridescenceThickness: iridescenceThickness,
  29770. ivec2: ivec2,
  29771. ivec3: ivec3,
  29772. ivec4: ivec4,
  29773. js: js,
  29774. label: label,
  29775. length: length,
  29776. lengthSq: lengthSq,
  29777. lessThan: lessThan,
  29778. lessThanEqual: lessThanEqual,
  29779. lightPosition: lightPosition,
  29780. lightProjectionUV: lightProjectionUV,
  29781. lightShadowMatrix: lightShadowMatrix,
  29782. lightTargetDirection: lightTargetDirection,
  29783. lightTargetPosition: lightTargetPosition,
  29784. lightViewPosition: lightViewPosition,
  29785. lightingContext: lightingContext,
  29786. lights: lights,
  29787. linearDepth: linearDepth,
  29788. linearToneMapping: linearToneMapping,
  29789. localId: localId,
  29790. log: log,
  29791. log2: log2,
  29792. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  29793. loop: loop,
  29794. luminance: luminance,
  29795. mat2: mat2,
  29796. mat3: mat3,
  29797. mat4: mat4,
  29798. matcapUV: matcapUV,
  29799. materialAO: materialAO,
  29800. materialAlphaTest: materialAlphaTest,
  29801. materialAnisotropy: materialAnisotropy,
  29802. materialAnisotropyVector: materialAnisotropyVector,
  29803. materialAttenuationColor: materialAttenuationColor,
  29804. materialAttenuationDistance: materialAttenuationDistance,
  29805. materialClearcoat: materialClearcoat,
  29806. materialClearcoatNormal: materialClearcoatNormal,
  29807. materialClearcoatRoughness: materialClearcoatRoughness,
  29808. materialColor: materialColor,
  29809. materialDispersion: materialDispersion,
  29810. materialEmissive: materialEmissive,
  29811. materialEnvIntensity: materialEnvIntensity,
  29812. materialEnvRotation: materialEnvRotation,
  29813. materialIOR: materialIOR,
  29814. materialIridescence: materialIridescence,
  29815. materialIridescenceIOR: materialIridescenceIOR,
  29816. materialIridescenceThickness: materialIridescenceThickness,
  29817. materialLightMap: materialLightMap,
  29818. materialLineDashOffset: materialLineDashOffset,
  29819. materialLineDashSize: materialLineDashSize,
  29820. materialLineGapSize: materialLineGapSize,
  29821. materialLineScale: materialLineScale,
  29822. materialLineWidth: materialLineWidth,
  29823. materialMetalness: materialMetalness,
  29824. materialNormal: materialNormal,
  29825. materialOpacity: materialOpacity,
  29826. materialPointSize: materialPointSize,
  29827. materialReference: materialReference,
  29828. materialReflectivity: materialReflectivity,
  29829. materialRefractionRatio: materialRefractionRatio,
  29830. materialRotation: materialRotation,
  29831. materialRoughness: materialRoughness,
  29832. materialSheen: materialSheen,
  29833. materialSheenRoughness: materialSheenRoughness,
  29834. materialShininess: materialShininess,
  29835. materialSpecular: materialSpecular,
  29836. materialSpecularColor: materialSpecularColor,
  29837. materialSpecularIntensity: materialSpecularIntensity,
  29838. materialSpecularStrength: materialSpecularStrength,
  29839. materialThickness: materialThickness,
  29840. materialTransmission: materialTransmission,
  29841. max: max$1,
  29842. maxMipLevel: maxMipLevel,
  29843. mediumpModelViewMatrix: mediumpModelViewMatrix,
  29844. metalness: metalness,
  29845. min: min$1,
  29846. mix: mix,
  29847. mixElement: mixElement,
  29848. mod: mod,
  29849. modInt: modInt,
  29850. modelDirection: modelDirection,
  29851. modelNormalMatrix: modelNormalMatrix,
  29852. modelPosition: modelPosition,
  29853. modelRadius: modelRadius,
  29854. modelScale: modelScale,
  29855. modelViewMatrix: modelViewMatrix,
  29856. modelViewPosition: modelViewPosition,
  29857. modelViewProjection: modelViewProjection,
  29858. modelWorldMatrix: modelWorldMatrix,
  29859. modelWorldMatrixInverse: modelWorldMatrixInverse,
  29860. morphReference: morphReference,
  29861. mrt: mrt,
  29862. mul: mul,
  29863. mx_aastep: mx_aastep,
  29864. mx_cell_noise_float: mx_cell_noise_float,
  29865. mx_contrast: mx_contrast,
  29866. mx_fractal_noise_float: mx_fractal_noise_float,
  29867. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  29868. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  29869. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  29870. mx_hsvtorgb: mx_hsvtorgb,
  29871. mx_noise_float: mx_noise_float,
  29872. mx_noise_vec3: mx_noise_vec3,
  29873. mx_noise_vec4: mx_noise_vec4,
  29874. mx_ramplr: mx_ramplr,
  29875. mx_ramptb: mx_ramptb,
  29876. mx_rgbtohsv: mx_rgbtohsv,
  29877. mx_safepower: mx_safepower,
  29878. mx_splitlr: mx_splitlr,
  29879. mx_splittb: mx_splittb,
  29880. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  29881. mx_transform_uv: mx_transform_uv,
  29882. mx_worley_noise_float: mx_worley_noise_float,
  29883. mx_worley_noise_vec2: mx_worley_noise_vec2,
  29884. mx_worley_noise_vec3: mx_worley_noise_vec3,
  29885. negate: negate,
  29886. neutralToneMapping: neutralToneMapping,
  29887. nodeArray: nodeArray,
  29888. nodeImmutable: nodeImmutable,
  29889. nodeObject: nodeObject,
  29890. nodeObjects: nodeObjects,
  29891. nodeProxy: nodeProxy,
  29892. normalFlat: normalFlat,
  29893. normalGeometry: normalGeometry,
  29894. normalLocal: normalLocal,
  29895. normalMap: normalMap,
  29896. normalView: normalView,
  29897. normalWorld: normalWorld,
  29898. normalize: normalize,
  29899. not: not,
  29900. notEqual: notEqual,
  29901. numWorkgroups: numWorkgroups,
  29902. objectDirection: objectDirection,
  29903. objectGroup: objectGroup,
  29904. objectPosition: objectPosition,
  29905. objectRadius: objectRadius,
  29906. objectScale: objectScale,
  29907. objectViewPosition: objectViewPosition,
  29908. objectWorldMatrix: objectWorldMatrix,
  29909. oneMinus: oneMinus,
  29910. or: or,
  29911. orthographicDepthToViewZ: orthographicDepthToViewZ,
  29912. oscSawtooth: oscSawtooth,
  29913. oscSine: oscSine,
  29914. oscSquare: oscSquare,
  29915. oscTriangle: oscTriangle,
  29916. output: output,
  29917. outputStruct: outputStruct,
  29918. overlay: overlay,
  29919. overloadingFn: overloadingFn,
  29920. parabola: parabola,
  29921. parallaxDirection: parallaxDirection,
  29922. parallaxUV: parallaxUV,
  29923. parameter: parameter,
  29924. pass: pass,
  29925. passTexture: passTexture,
  29926. pcurve: pcurve,
  29927. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  29928. pmremTexture: pmremTexture,
  29929. pointShadow: pointShadow,
  29930. pointUV: pointUV,
  29931. pointWidth: pointWidth,
  29932. positionGeometry: positionGeometry,
  29933. positionLocal: positionLocal,
  29934. positionPrevious: positionPrevious,
  29935. positionView: positionView,
  29936. positionViewDirection: positionViewDirection,
  29937. positionWorld: positionWorld,
  29938. positionWorldDirection: positionWorldDirection,
  29939. posterize: posterize,
  29940. pow: pow,
  29941. pow2: pow2,
  29942. pow3: pow3,
  29943. pow4: pow4,
  29944. property: property,
  29945. radians: radians,
  29946. rand: rand,
  29947. range: range,
  29948. rangeFog: rangeFog,
  29949. rangeFogFactor: rangeFogFactor,
  29950. reciprocal: reciprocal,
  29951. reference: reference,
  29952. referenceBuffer: referenceBuffer,
  29953. reflect: reflect,
  29954. reflectVector: reflectVector,
  29955. reflectView: reflectView,
  29956. reflector: reflector,
  29957. refract: refract,
  29958. refractVector: refractVector,
  29959. refractView: refractView,
  29960. reinhardToneMapping: reinhardToneMapping,
  29961. remainder: remainder,
  29962. remap: remap,
  29963. remapClamp: remapClamp,
  29964. renderGroup: renderGroup,
  29965. renderOutput: renderOutput,
  29966. rendererReference: rendererReference,
  29967. rotate: rotate,
  29968. rotateUV: rotateUV,
  29969. roughness: roughness,
  29970. round: round,
  29971. rtt: rtt,
  29972. sRGBTransferEOTF: sRGBTransferEOTF,
  29973. sRGBTransferOETF: sRGBTransferOETF,
  29974. sampler: sampler,
  29975. samplerComparison: samplerComparison,
  29976. saturate: saturate,
  29977. saturation: saturation,
  29978. screen: screen,
  29979. screenCoordinate: screenCoordinate,
  29980. screenSize: screenSize,
  29981. screenUV: screenUV,
  29982. scriptable: scriptable,
  29983. scriptableValue: scriptableValue,
  29984. select: select,
  29985. setCurrentStack: setCurrentStack,
  29986. shaderStages: shaderStages,
  29987. shadow: shadow,
  29988. shadowPositionWorld: shadowPositionWorld,
  29989. shapeCircle: shapeCircle,
  29990. sharedUniformGroup: sharedUniformGroup,
  29991. sheen: sheen,
  29992. sheenRoughness: sheenRoughness,
  29993. shiftLeft: shiftLeft,
  29994. shiftRight: shiftRight,
  29995. shininess: shininess,
  29996. sign: sign,
  29997. sin: sin,
  29998. sinc: sinc,
  29999. skinning: skinning,
  30000. smoothstep: smoothstep,
  30001. smoothstepElement: smoothstepElement,
  30002. specularColor: specularColor,
  30003. specularF90: specularF90,
  30004. spherizeUV: spherizeUV,
  30005. split: split,
  30006. spritesheetUV: spritesheetUV,
  30007. sqrt: sqrt,
  30008. stack: stack,
  30009. step: step,
  30010. storage: storage,
  30011. storageBarrier: storageBarrier,
  30012. storageObject: storageObject,
  30013. storageTexture: storageTexture,
  30014. string: string,
  30015. struct: struct,
  30016. sub: sub,
  30017. subgroupIndex: subgroupIndex,
  30018. subgroupSize: subgroupSize,
  30019. tan: tan,
  30020. tangentGeometry: tangentGeometry,
  30021. tangentLocal: tangentLocal,
  30022. tangentView: tangentView,
  30023. tangentWorld: tangentWorld,
  30024. temp: temp,
  30025. texture: texture,
  30026. texture3D: texture3D,
  30027. textureBarrier: textureBarrier,
  30028. textureBicubic: textureBicubic,
  30029. textureCubeUV: textureCubeUV,
  30030. textureLoad: textureLoad,
  30031. textureSize: textureSize,
  30032. textureStore: textureStore,
  30033. thickness: thickness,
  30034. time: time,
  30035. timerDelta: timerDelta,
  30036. timerGlobal: timerGlobal,
  30037. timerLocal: timerLocal,
  30038. toOutputColorSpace: toOutputColorSpace,
  30039. toWorkingColorSpace: toWorkingColorSpace,
  30040. toneMapping: toneMapping,
  30041. toneMappingExposure: toneMappingExposure,
  30042. toonOutlinePass: toonOutlinePass,
  30043. transformDirection: transformDirection,
  30044. transformNormal: transformNormal,
  30045. transformNormalToView: transformNormalToView,
  30046. transformedBentNormalView: transformedBentNormalView,
  30047. transformedBitangentView: transformedBitangentView,
  30048. transformedBitangentWorld: transformedBitangentWorld,
  30049. transformedClearcoatNormalView: transformedClearcoatNormalView,
  30050. transformedNormalView: transformedNormalView,
  30051. transformedNormalWorld: transformedNormalWorld,
  30052. transformedTangentView: transformedTangentView,
  30053. transformedTangentWorld: transformedTangentWorld,
  30054. transmission: transmission,
  30055. transpose: transpose,
  30056. triNoise3D: triNoise3D,
  30057. triplanarTexture: triplanarTexture,
  30058. triplanarTextures: triplanarTextures,
  30059. trunc: trunc,
  30060. tslFn: tslFn,
  30061. uint: uint,
  30062. uniform: uniform,
  30063. uniformArray: uniformArray,
  30064. uniformGroup: uniformGroup,
  30065. uniforms: uniforms,
  30066. userData: userData,
  30067. uv: uv,
  30068. uvec2: uvec2,
  30069. uvec3: uvec3,
  30070. uvec4: uvec4,
  30071. varying: varying,
  30072. varyingProperty: varyingProperty,
  30073. vec2: vec2,
  30074. vec3: vec3,
  30075. vec4: vec4,
  30076. vectorComponents: vectorComponents,
  30077. velocity: velocity,
  30078. vertexColor: vertexColor,
  30079. vertexIndex: vertexIndex,
  30080. vertexStage: vertexStage,
  30081. vibrance: vibrance,
  30082. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  30083. viewZToOrthographicDepth: viewZToOrthographicDepth,
  30084. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  30085. viewport: viewport,
  30086. viewportBottomLeft: viewportBottomLeft,
  30087. viewportCoordinate: viewportCoordinate,
  30088. viewportDepthTexture: viewportDepthTexture,
  30089. viewportLinearDepth: viewportLinearDepth,
  30090. viewportMipTexture: viewportMipTexture,
  30091. viewportResolution: viewportResolution,
  30092. viewportSafeUV: viewportSafeUV,
  30093. viewportSharedTexture: viewportSharedTexture,
  30094. viewportSize: viewportSize,
  30095. viewportTexture: viewportTexture,
  30096. viewportTopLeft: viewportTopLeft,
  30097. viewportUV: viewportUV,
  30098. wgsl: wgsl,
  30099. wgslFn: wgslFn,
  30100. workgroupArray: workgroupArray,
  30101. workgroupBarrier: workgroupBarrier,
  30102. workgroupId: workgroupId,
  30103. workingToColorSpace: workingToColorSpace,
  30104. xor: xor
  30105. });
  30106. const _clearColor = /*@__PURE__*/ new Color4();
  30107. /**
  30108. * This renderer module manages the background.
  30109. *
  30110. * @private
  30111. * @augments DataMap
  30112. */
  30113. class Background extends DataMap {
  30114. /**
  30115. * Constructs a new background management component.
  30116. *
  30117. * @param {Renderer} renderer - The renderer.
  30118. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  30119. */
  30120. constructor( renderer, nodes ) {
  30121. super();
  30122. /**
  30123. * The renderer.
  30124. *
  30125. * @type {Renderer}
  30126. */
  30127. this.renderer = renderer;
  30128. /**
  30129. * Renderer component for managing nodes related logic.
  30130. *
  30131. * @type {Nodes}
  30132. */
  30133. this.nodes = nodes;
  30134. }
  30135. /**
  30136. * Updates the background for the given scene. Depending on how `Scene.background`
  30137. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  30138. * or add a mesh to the render list for rendering the background as a textured plane
  30139. * or skybox.
  30140. *
  30141. * @param {Scene} scene - The scene.
  30142. * @param {RenderList} renderList - The current render list.
  30143. * @param {RenderContext} renderContext - The current render context.
  30144. */
  30145. update( scene, renderList, renderContext ) {
  30146. const renderer = this.renderer;
  30147. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  30148. let forceClear = false;
  30149. if ( background === null ) {
  30150. // no background settings, use clear color configuration from the renderer
  30151. renderer._clearColor.getRGB( _clearColor );
  30152. _clearColor.a = renderer._clearColor.a;
  30153. } else if ( background.isColor === true ) {
  30154. // background is an opaque color
  30155. background.getRGB( _clearColor );
  30156. _clearColor.a = 1;
  30157. forceClear = true;
  30158. } else if ( background.isNode === true ) {
  30159. const sceneData = this.get( scene );
  30160. const backgroundNode = background;
  30161. _clearColor.copy( renderer._clearColor );
  30162. let backgroundMesh = sceneData.backgroundMesh;
  30163. if ( backgroundMesh === undefined ) {
  30164. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  30165. // @TODO: Add Texture2D support using node context
  30166. getUV: () => backgroundRotation.mul( normalWorld ),
  30167. getTextureLevel: () => backgroundBlurriness
  30168. } );
  30169. let viewProj = modelViewProjection;
  30170. viewProj = viewProj.setZ( viewProj.w );
  30171. const nodeMaterial = new NodeMaterial();
  30172. nodeMaterial.name = 'Background.material';
  30173. nodeMaterial.side = BackSide;
  30174. nodeMaterial.depthTest = false;
  30175. nodeMaterial.depthWrite = false;
  30176. nodeMaterial.allowOverride = false;
  30177. nodeMaterial.fog = false;
  30178. nodeMaterial.lights = false;
  30179. nodeMaterial.vertexNode = viewProj;
  30180. nodeMaterial.colorNode = backgroundMeshNode;
  30181. sceneData.backgroundMeshNode = backgroundMeshNode;
  30182. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  30183. backgroundMesh.frustumCulled = false;
  30184. backgroundMesh.name = 'Background.mesh';
  30185. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  30186. this.matrixWorld.copyPosition( camera.matrixWorld );
  30187. };
  30188. function onBackgroundDispose() {
  30189. background.removeEventListener( 'dispose', onBackgroundDispose );
  30190. backgroundMesh.material.dispose();
  30191. backgroundMesh.geometry.dispose();
  30192. }
  30193. background.addEventListener( 'dispose', onBackgroundDispose );
  30194. }
  30195. const backgroundCacheKey = backgroundNode.getCacheKey();
  30196. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  30197. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  30198. sceneData.backgroundMeshNode.needsUpdate = true;
  30199. backgroundMesh.material.needsUpdate = true;
  30200. sceneData.backgroundCacheKey = backgroundCacheKey;
  30201. }
  30202. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  30203. } else {
  30204. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  30205. }
  30206. //
  30207. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  30208. if ( environmentBlendMode === 'additive' ) {
  30209. _clearColor.set( 0, 0, 0, 1 );
  30210. } else if ( environmentBlendMode === 'alpha-blend' ) {
  30211. _clearColor.set( 0, 0, 0, 0 );
  30212. }
  30213. //
  30214. if ( renderer.autoClear === true || forceClear === true ) {
  30215. const clearColorValue = renderContext.clearColorValue;
  30216. clearColorValue.r = _clearColor.r;
  30217. clearColorValue.g = _clearColor.g;
  30218. clearColorValue.b = _clearColor.b;
  30219. clearColorValue.a = _clearColor.a;
  30220. // premultiply alpha
  30221. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  30222. clearColorValue.r *= clearColorValue.a;
  30223. clearColorValue.g *= clearColorValue.a;
  30224. clearColorValue.b *= clearColorValue.a;
  30225. }
  30226. //
  30227. renderContext.depthClearValue = renderer._clearDepth;
  30228. renderContext.stencilClearValue = renderer._clearStencil;
  30229. renderContext.clearColor = renderer.autoClearColor === true;
  30230. renderContext.clearDepth = renderer.autoClearDepth === true;
  30231. renderContext.clearStencil = renderer.autoClearStencil === true;
  30232. } else {
  30233. renderContext.clearColor = false;
  30234. renderContext.clearDepth = false;
  30235. renderContext.clearStencil = false;
  30236. }
  30237. }
  30238. }
  30239. let _id$6 = 0;
  30240. /**
  30241. * A bind group represents a collection of bindings and thus a collection
  30242. * or resources. Bind groups are assigned to pipelines to provide them
  30243. * with the required resources (like uniform buffers or textures).
  30244. *
  30245. * @private
  30246. */
  30247. class BindGroup {
  30248. /**
  30249. * Constructs a new bind group.
  30250. *
  30251. * @param {string} name - The bind group's name.
  30252. * @param {Array<Binding>} bindings - An array of bindings.
  30253. * @param {number} index - The group index.
  30254. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  30255. */
  30256. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30257. /**
  30258. * The bind group's name.
  30259. *
  30260. * @type {string}
  30261. */
  30262. this.name = name;
  30263. /**
  30264. * An array of bindings.
  30265. *
  30266. * @type {Array<Binding>}
  30267. */
  30268. this.bindings = bindings;
  30269. /**
  30270. * The group index.
  30271. *
  30272. * @type {number}
  30273. */
  30274. this.index = index;
  30275. /**
  30276. * An array of reference bindings.
  30277. *
  30278. * @type {Array<Binding>}
  30279. */
  30280. this.bindingsReference = bindingsReference;
  30281. /**
  30282. * The group's ID.
  30283. *
  30284. * @type {number}
  30285. */
  30286. this.id = _id$6 ++;
  30287. }
  30288. }
  30289. /**
  30290. * This module represents the state of a node builder after it was
  30291. * used to build the nodes for a render object. The state holds the
  30292. * results of the build for further processing in the renderer.
  30293. *
  30294. * Render objects with identical cache keys share the same node builder state.
  30295. *
  30296. * @private
  30297. */
  30298. class NodeBuilderState {
  30299. /**
  30300. * Constructs a new node builder state.
  30301. *
  30302. * @param {string} vertexShader - The native vertex shader code.
  30303. * @param {string} fragmentShader - The native fragment shader code.
  30304. * @param {string} computeShader - The native compute shader code.
  30305. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  30306. * @param {Array<BindGroup>} bindings - An array of bind groups.
  30307. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  30308. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  30309. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  30310. * @param {NodeMaterialObserver} observer - A node material observer.
  30311. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  30312. */
  30313. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  30314. /**
  30315. * The native vertex shader code.
  30316. *
  30317. * @type {string}
  30318. */
  30319. this.vertexShader = vertexShader;
  30320. /**
  30321. * The native fragment shader code.
  30322. *
  30323. * @type {string}
  30324. */
  30325. this.fragmentShader = fragmentShader;
  30326. /**
  30327. * The native compute shader code.
  30328. *
  30329. * @type {string}
  30330. */
  30331. this.computeShader = computeShader;
  30332. /**
  30333. * An array with transform attribute objects.
  30334. * Only relevant when using compute shaders with WebGL 2.
  30335. *
  30336. * @type {Array<Object>}
  30337. */
  30338. this.transforms = transforms;
  30339. /**
  30340. * An array of node attributes representing
  30341. * the attributes of the shaders.
  30342. *
  30343. * @type {Array<NodeAttribute>}
  30344. */
  30345. this.nodeAttributes = nodeAttributes;
  30346. /**
  30347. * An array of bind groups representing the uniform or storage
  30348. * buffers, texture or samplers of the shader.
  30349. *
  30350. * @type {Array<BindGroup>}
  30351. */
  30352. this.bindings = bindings;
  30353. /**
  30354. * An array of nodes that implement their `update()` method.
  30355. *
  30356. * @type {Array<Node>}
  30357. */
  30358. this.updateNodes = updateNodes;
  30359. /**
  30360. * An array of nodes that implement their `updateBefore()` method.
  30361. *
  30362. * @type {Array<Node>}
  30363. */
  30364. this.updateBeforeNodes = updateBeforeNodes;
  30365. /**
  30366. * An array of nodes that implement their `updateAfter()` method.
  30367. *
  30368. * @type {Array<Node>}
  30369. */
  30370. this.updateAfterNodes = updateAfterNodes;
  30371. /**
  30372. * A node material observer.
  30373. *
  30374. * @type {NodeMaterialObserver}
  30375. */
  30376. this.observer = observer;
  30377. /**
  30378. * How often this state is used by render objects.
  30379. *
  30380. * @type {number}
  30381. */
  30382. this.usedTimes = 0;
  30383. }
  30384. /**
  30385. * This method is used to create a array of bind groups based
  30386. * on the existing bind groups of this state. Shared groups are
  30387. * not cloned.
  30388. *
  30389. * @return {Array<BindGroup>} A array of bind groups.
  30390. */
  30391. createBindings() {
  30392. const bindings = [];
  30393. for ( const instanceGroup of this.bindings ) {
  30394. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  30395. if ( shared !== true ) {
  30396. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  30397. bindings.push( bindingsGroup );
  30398. for ( const instanceBinding of instanceGroup.bindings ) {
  30399. bindingsGroup.bindings.push( instanceBinding.clone() );
  30400. }
  30401. } else {
  30402. bindings.push( instanceGroup );
  30403. }
  30404. }
  30405. return bindings;
  30406. }
  30407. }
  30408. /**
  30409. * {@link NodeBuilder} is going to create instances of this class during the build process
  30410. * of nodes. They represent the final shader attributes that are going to be generated
  30411. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  30412. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  30413. */
  30414. class NodeAttribute {
  30415. /**
  30416. * Constructs a new node attribute.
  30417. *
  30418. * @param {string} name - The name of the attribute.
  30419. * @param {string} type - The type of the attribute.
  30420. * @param {?Node} node - An optional reference to the node.
  30421. */
  30422. constructor( name, type, node = null ) {
  30423. /**
  30424. * This flag can be used for type testing.
  30425. *
  30426. * @type {boolean}
  30427. * @readonly
  30428. * @default true
  30429. */
  30430. this.isNodeAttribute = true;
  30431. /**
  30432. * The name of the attribute.
  30433. *
  30434. * @type {string}
  30435. */
  30436. this.name = name;
  30437. /**
  30438. * The type of the attribute.
  30439. *
  30440. * @type {string}
  30441. */
  30442. this.type = type;
  30443. /**
  30444. * An optional reference to the node.
  30445. *
  30446. * @type {?Node}
  30447. * @default null
  30448. */
  30449. this.node = node;
  30450. }
  30451. }
  30452. /**
  30453. * {@link NodeBuilder} is going to create instances of this class during the build process
  30454. * of nodes. They represent the final shader uniforms that are going to be generated
  30455. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  30456. * for this purpose.
  30457. */
  30458. class NodeUniform {
  30459. /**
  30460. * Constructs a new node uniform.
  30461. *
  30462. * @param {string} name - The name of the uniform.
  30463. * @param {string} type - The type of the uniform.
  30464. * @param {UniformNode} node - An reference to the node.
  30465. */
  30466. constructor( name, type, node ) {
  30467. /**
  30468. * This flag can be used for type testing.
  30469. *
  30470. * @type {boolean}
  30471. * @readonly
  30472. * @default true
  30473. */
  30474. this.isNodeUniform = true;
  30475. /**
  30476. * The name of the uniform.
  30477. *
  30478. * @type {string}
  30479. */
  30480. this.name = name;
  30481. /**
  30482. * The type of the uniform.
  30483. *
  30484. * @type {string}
  30485. */
  30486. this.type = type;
  30487. /**
  30488. * An reference to the node.
  30489. *
  30490. * @type {UniformNode}
  30491. */
  30492. this.node = node.getSelf();
  30493. }
  30494. /**
  30495. * The value of the uniform node.
  30496. *
  30497. * @type {any}
  30498. */
  30499. get value() {
  30500. return this.node.value;
  30501. }
  30502. set value( val ) {
  30503. this.node.value = val;
  30504. }
  30505. /**
  30506. * The id of the uniform node.
  30507. *
  30508. * @type {number}
  30509. */
  30510. get id() {
  30511. return this.node.id;
  30512. }
  30513. /**
  30514. * The uniform node's group.
  30515. *
  30516. * @type {UniformGroupNode}
  30517. */
  30518. get groupNode() {
  30519. return this.node.groupNode;
  30520. }
  30521. }
  30522. /**
  30523. * {@link NodeBuilder} is going to create instances of this class during the build process
  30524. * of nodes. They represent the final shader variables that are going to be generated
  30525. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  30526. * this purpose.
  30527. */
  30528. class NodeVar {
  30529. /**
  30530. * Constructs a new node variable.
  30531. *
  30532. * @param {string} name - The name of the variable.
  30533. * @param {string} type - The type of the variable.
  30534. * @param {boolean} [readOnly=false] - The read-only flag.
  30535. * @param {?number} [count=null] - The size.
  30536. */
  30537. constructor( name, type, readOnly = false, count = null ) {
  30538. /**
  30539. * This flag can be used for type testing.
  30540. *
  30541. * @type {boolean}
  30542. * @readonly
  30543. * @default true
  30544. */
  30545. this.isNodeVar = true;
  30546. /**
  30547. * The name of the variable.
  30548. *
  30549. * @type {string}
  30550. */
  30551. this.name = name;
  30552. /**
  30553. * The type of the variable.
  30554. *
  30555. * @type {string}
  30556. */
  30557. this.type = type;
  30558. /**
  30559. * The read-only flag.
  30560. *
  30561. * @type {boolean}
  30562. */
  30563. this.readOnly = readOnly;
  30564. /**
  30565. * The size.
  30566. *
  30567. * @type {?number}
  30568. */
  30569. this.count = count;
  30570. }
  30571. }
  30572. /**
  30573. * {@link NodeBuilder} is going to create instances of this class during the build process
  30574. * of nodes. They represent the final shader varyings that are going to be generated
  30575. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  30576. * this purpose.
  30577. *
  30578. * @augments NodeVar
  30579. */
  30580. class NodeVarying extends NodeVar {
  30581. /**
  30582. * Constructs a new node varying.
  30583. *
  30584. * @param {string} name - The name of the varying.
  30585. * @param {string} type - The type of the varying.
  30586. * @param {?string} interpolationType - The interpolation type of the varying.
  30587. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  30588. */
  30589. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  30590. super( name, type );
  30591. /**
  30592. * Whether this varying requires interpolation or not. This property can be used
  30593. * to check if the varying can be optimized for a variable.
  30594. *
  30595. * @type {boolean}
  30596. * @default false
  30597. */
  30598. this.needsInterpolation = false;
  30599. /**
  30600. * This flag can be used for type testing.
  30601. *
  30602. * @type {boolean}
  30603. * @readonly
  30604. * @default true
  30605. */
  30606. this.isNodeVarying = true;
  30607. /**
  30608. * The interpolation type of the varying data.
  30609. *
  30610. * @type {?string}
  30611. * @default null
  30612. */
  30613. this.interpolationType = interpolationType;
  30614. /**
  30615. * The interpolation sampling type of varying data.
  30616. *
  30617. * @type {?string}
  30618. * @default null
  30619. */
  30620. this.interpolationSampling = interpolationSampling;
  30621. }
  30622. }
  30623. /**
  30624. * {@link NodeBuilder} is going to create instances of this class during the build process
  30625. * of nodes. They represent user-defined, native shader code portions that are going to be
  30626. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  30627. * for this purpose.
  30628. */
  30629. class NodeCode {
  30630. /**
  30631. * Constructs a new code node.
  30632. *
  30633. * @param {string} name - The name of the code.
  30634. * @param {string} type - The node type.
  30635. * @param {string} [code=''] - The native shader code.
  30636. */
  30637. constructor( name, type, code = '' ) {
  30638. /**
  30639. * The name of the code.
  30640. *
  30641. * @type {string}
  30642. */
  30643. this.name = name;
  30644. /**
  30645. * The node type.
  30646. *
  30647. * @type {string}
  30648. */
  30649. this.type = type;
  30650. /**
  30651. * The native shader code.
  30652. *
  30653. * @type {string}
  30654. * @default ''
  30655. */
  30656. this.code = code;
  30657. Object.defineProperty( this, 'isNodeCode', { value: true } );
  30658. }
  30659. }
  30660. let _id$5 = 0;
  30661. /**
  30662. * This utility class is used in {@link NodeBuilder} as an internal
  30663. * cache data structure for node data.
  30664. */
  30665. class NodeCache {
  30666. /**
  30667. * Constructs a new node cache.
  30668. *
  30669. * @param {?NodeCache} parent - A reference to a parent cache.
  30670. */
  30671. constructor( parent = null ) {
  30672. /**
  30673. * The id of the cache.
  30674. *
  30675. * @type {number}
  30676. * @readonly
  30677. */
  30678. this.id = _id$5 ++;
  30679. /**
  30680. * A weak map for managing node data.
  30681. *
  30682. * @type {WeakMap<Node, Object>}
  30683. */
  30684. this.nodesData = new WeakMap();
  30685. /**
  30686. * Reference to a parent node cache.
  30687. *
  30688. * @type {?NodeCache}
  30689. * @default null
  30690. */
  30691. this.parent = parent;
  30692. }
  30693. /**
  30694. * Returns the data for the given node.
  30695. *
  30696. * @param {Node} node - The node.
  30697. * @return {?Object} The data for the node.
  30698. */
  30699. getData( node ) {
  30700. let data = this.nodesData.get( node );
  30701. if ( data === undefined && this.parent !== null ) {
  30702. data = this.parent.getData( node );
  30703. }
  30704. return data;
  30705. }
  30706. /**
  30707. * Sets the data for a given node.
  30708. *
  30709. * @param {Node} node - The node.
  30710. * @param {Object} data - The data that should be cached.
  30711. */
  30712. setData( node, data ) {
  30713. this.nodesData.set( node, data );
  30714. }
  30715. }
  30716. class StructType {
  30717. constructor( name, members ) {
  30718. this.name = name;
  30719. this.members = members;
  30720. this.output = false;
  30721. }
  30722. }
  30723. /**
  30724. * Abstract base class for uniforms.
  30725. *
  30726. * @abstract
  30727. * @private
  30728. */
  30729. class Uniform {
  30730. /**
  30731. * Constructs a new uniform.
  30732. *
  30733. * @param {string} name - The uniform's name.
  30734. * @param {any} value - The uniform's value.
  30735. */
  30736. constructor( name, value ) {
  30737. /**
  30738. * The uniform's name.
  30739. *
  30740. * @type {string}
  30741. */
  30742. this.name = name;
  30743. /**
  30744. * The uniform's value.
  30745. *
  30746. * @type {any}
  30747. */
  30748. this.value = value;
  30749. /**
  30750. * Used to build the uniform buffer according to the STD140 layout.
  30751. * Derived uniforms will set this property to a data type specific
  30752. * value.
  30753. *
  30754. * @type {number}
  30755. */
  30756. this.boundary = 0;
  30757. /**
  30758. * The item size. Derived uniforms will set this property to a data
  30759. * type specific value.
  30760. *
  30761. * @type {number}
  30762. */
  30763. this.itemSize = 0;
  30764. /**
  30765. * This property is set by {@link UniformsGroup} and marks
  30766. * the start position in the uniform buffer.
  30767. *
  30768. * @type {number}
  30769. */
  30770. this.offset = 0;
  30771. }
  30772. /**
  30773. * Sets the uniform's value.
  30774. *
  30775. * @param {any} value - The value to set.
  30776. */
  30777. setValue( value ) {
  30778. this.value = value;
  30779. }
  30780. /**
  30781. * Returns the uniform's value.
  30782. *
  30783. * @return {any} The value.
  30784. */
  30785. getValue() {
  30786. return this.value;
  30787. }
  30788. }
  30789. /**
  30790. * Represents a Number uniform.
  30791. *
  30792. * @private
  30793. * @augments Uniform
  30794. */
  30795. class NumberUniform extends Uniform {
  30796. /**
  30797. * Constructs a new Number uniform.
  30798. *
  30799. * @param {string} name - The uniform's name.
  30800. * @param {number} value - The uniform's value.
  30801. */
  30802. constructor( name, value = 0 ) {
  30803. super( name, value );
  30804. /**
  30805. * This flag can be used for type testing.
  30806. *
  30807. * @type {boolean}
  30808. * @readonly
  30809. * @default true
  30810. */
  30811. this.isNumberUniform = true;
  30812. this.boundary = 4;
  30813. this.itemSize = 1;
  30814. }
  30815. }
  30816. /**
  30817. * Represents a Vector2 uniform.
  30818. *
  30819. * @private
  30820. * @augments Uniform
  30821. */
  30822. class Vector2Uniform extends Uniform {
  30823. /**
  30824. * Constructs a new Number uniform.
  30825. *
  30826. * @param {string} name - The uniform's name.
  30827. * @param {Vector2} value - The uniform's value.
  30828. */
  30829. constructor( name, value = new Vector2() ) {
  30830. super( name, value );
  30831. /**
  30832. * This flag can be used for type testing.
  30833. *
  30834. * @type {boolean}
  30835. * @readonly
  30836. * @default true
  30837. */
  30838. this.isVector2Uniform = true;
  30839. this.boundary = 8;
  30840. this.itemSize = 2;
  30841. }
  30842. }
  30843. /**
  30844. * Represents a Vector3 uniform.
  30845. *
  30846. * @private
  30847. * @augments Uniform
  30848. */
  30849. class Vector3Uniform extends Uniform {
  30850. /**
  30851. * Constructs a new Number uniform.
  30852. *
  30853. * @param {string} name - The uniform's name.
  30854. * @param {Vector3} value - The uniform's value.
  30855. */
  30856. constructor( name, value = new Vector3() ) {
  30857. super( name, value );
  30858. /**
  30859. * This flag can be used for type testing.
  30860. *
  30861. * @type {boolean}
  30862. * @readonly
  30863. * @default true
  30864. */
  30865. this.isVector3Uniform = true;
  30866. this.boundary = 16;
  30867. this.itemSize = 3;
  30868. }
  30869. }
  30870. /**
  30871. * Represents a Vector4 uniform.
  30872. *
  30873. * @private
  30874. * @augments Uniform
  30875. */
  30876. class Vector4Uniform extends Uniform {
  30877. /**
  30878. * Constructs a new Number uniform.
  30879. *
  30880. * @param {string} name - The uniform's name.
  30881. * @param {Vector4} value - The uniform's value.
  30882. */
  30883. constructor( name, value = new Vector4() ) {
  30884. super( name, value );
  30885. /**
  30886. * This flag can be used for type testing.
  30887. *
  30888. * @type {boolean}
  30889. * @readonly
  30890. * @default true
  30891. */
  30892. this.isVector4Uniform = true;
  30893. this.boundary = 16;
  30894. this.itemSize = 4;
  30895. }
  30896. }
  30897. /**
  30898. * Represents a Color uniform.
  30899. *
  30900. * @private
  30901. * @augments Uniform
  30902. */
  30903. class ColorUniform extends Uniform {
  30904. /**
  30905. * Constructs a new Number uniform.
  30906. *
  30907. * @param {string} name - The uniform's name.
  30908. * @param {Color} value - The uniform's value.
  30909. */
  30910. constructor( name, value = new Color() ) {
  30911. super( name, value );
  30912. /**
  30913. * This flag can be used for type testing.
  30914. *
  30915. * @type {boolean}
  30916. * @readonly
  30917. * @default true
  30918. */
  30919. this.isColorUniform = true;
  30920. this.boundary = 16;
  30921. this.itemSize = 3;
  30922. }
  30923. }
  30924. /**
  30925. * Represents a Matrix2 uniform.
  30926. *
  30927. * @private
  30928. * @augments Uniform
  30929. */
  30930. class Matrix2Uniform extends Uniform {
  30931. /**
  30932. * Constructs a new Number uniform.
  30933. *
  30934. * @param {string} name - The uniform's name.
  30935. * @param {Matrix2} value - The uniform's value.
  30936. */
  30937. constructor( name, value = new Matrix2() ) {
  30938. super( name, value );
  30939. /**
  30940. * This flag can be used for type testing.
  30941. *
  30942. * @type {boolean}
  30943. * @readonly
  30944. * @default true
  30945. */
  30946. this.isMatrix2Uniform = true;
  30947. this.boundary = 16;
  30948. this.itemSize = 4;
  30949. }
  30950. }
  30951. /**
  30952. * Represents a Matrix3 uniform.
  30953. *
  30954. * @private
  30955. * @augments Uniform
  30956. */
  30957. class Matrix3Uniform extends Uniform {
  30958. /**
  30959. * Constructs a new Number uniform.
  30960. *
  30961. * @param {string} name - The uniform's name.
  30962. * @param {Matrix3} value - The uniform's value.
  30963. */
  30964. constructor( name, value = new Matrix3() ) {
  30965. super( name, value );
  30966. /**
  30967. * This flag can be used for type testing.
  30968. *
  30969. * @type {boolean}
  30970. * @readonly
  30971. * @default true
  30972. */
  30973. this.isMatrix3Uniform = true;
  30974. this.boundary = 48;
  30975. this.itemSize = 12;
  30976. }
  30977. }
  30978. /**
  30979. * Represents a Matrix4 uniform.
  30980. *
  30981. * @private
  30982. * @augments Uniform
  30983. */
  30984. class Matrix4Uniform extends Uniform {
  30985. /**
  30986. * Constructs a new Number uniform.
  30987. *
  30988. * @param {string} name - The uniform's name.
  30989. * @param {Matrix4} value - The uniform's value.
  30990. */
  30991. constructor( name, value = new Matrix4() ) {
  30992. super( name, value );
  30993. /**
  30994. * This flag can be used for type testing.
  30995. *
  30996. * @type {boolean}
  30997. * @readonly
  30998. * @default true
  30999. */
  31000. this.isMatrix4Uniform = true;
  31001. this.boundary = 64;
  31002. this.itemSize = 16;
  31003. }
  31004. }
  31005. /**
  31006. * A special form of Number uniform binding type.
  31007. * It's value is managed by a node object.
  31008. *
  31009. * @private
  31010. * @augments NumberUniform
  31011. */
  31012. class NumberNodeUniform extends NumberUniform {
  31013. /**
  31014. * Constructs a new node-based Number uniform.
  31015. *
  31016. * @param {NodeUniform} nodeUniform - The node uniform.
  31017. */
  31018. constructor( nodeUniform ) {
  31019. super( nodeUniform.name, nodeUniform.value );
  31020. /**
  31021. * The node uniform.
  31022. *
  31023. * @type {NodeUniform}
  31024. */
  31025. this.nodeUniform = nodeUniform;
  31026. }
  31027. /**
  31028. * Overwritten to return the value of the node uniform.
  31029. *
  31030. * @return {number} The value.
  31031. */
  31032. getValue() {
  31033. return this.nodeUniform.value;
  31034. }
  31035. /**
  31036. * Returns the node uniform data type.
  31037. *
  31038. * @return {string} The data type.
  31039. */
  31040. getType() {
  31041. return this.nodeUniform.type;
  31042. }
  31043. }
  31044. /**
  31045. * A special form of Vector2 uniform binding type.
  31046. * It's value is managed by a node object.
  31047. *
  31048. * @private
  31049. * @augments Vector2Uniform
  31050. */
  31051. class Vector2NodeUniform extends Vector2Uniform {
  31052. /**
  31053. * Constructs a new node-based Vector2 uniform.
  31054. *
  31055. * @param {NodeUniform} nodeUniform - The node uniform.
  31056. */
  31057. constructor( nodeUniform ) {
  31058. super( nodeUniform.name, nodeUniform.value );
  31059. /**
  31060. * The node uniform.
  31061. *
  31062. * @type {NodeUniform}
  31063. */
  31064. this.nodeUniform = nodeUniform;
  31065. }
  31066. /**
  31067. * Overwritten to return the value of the node uniform.
  31068. *
  31069. * @return {Vector2} The value.
  31070. */
  31071. getValue() {
  31072. return this.nodeUniform.value;
  31073. }
  31074. /**
  31075. * Returns the node uniform data type.
  31076. *
  31077. * @return {string} The data type.
  31078. */
  31079. getType() {
  31080. return this.nodeUniform.type;
  31081. }
  31082. }
  31083. /**
  31084. * A special form of Vector3 uniform binding type.
  31085. * It's value is managed by a node object.
  31086. *
  31087. * @private
  31088. * @augments Vector3Uniform
  31089. */
  31090. class Vector3NodeUniform extends Vector3Uniform {
  31091. /**
  31092. * Constructs a new node-based Vector3 uniform.
  31093. *
  31094. * @param {NodeUniform} nodeUniform - The node uniform.
  31095. */
  31096. constructor( nodeUniform ) {
  31097. super( nodeUniform.name, nodeUniform.value );
  31098. /**
  31099. * The node uniform.
  31100. *
  31101. * @type {NodeUniform}
  31102. */
  31103. this.nodeUniform = nodeUniform;
  31104. }
  31105. /**
  31106. * Overwritten to return the value of the node uniform.
  31107. *
  31108. * @return {Vector3} The value.
  31109. */
  31110. getValue() {
  31111. return this.nodeUniform.value;
  31112. }
  31113. /**
  31114. * Returns the node uniform data type.
  31115. *
  31116. * @return {string} The data type.
  31117. */
  31118. getType() {
  31119. return this.nodeUniform.type;
  31120. }
  31121. }
  31122. /**
  31123. * A special form of Vector4 uniform binding type.
  31124. * It's value is managed by a node object.
  31125. *
  31126. * @private
  31127. * @augments Vector4Uniform
  31128. */
  31129. class Vector4NodeUniform extends Vector4Uniform {
  31130. /**
  31131. * Constructs a new node-based Vector4 uniform.
  31132. *
  31133. * @param {NodeUniform} nodeUniform - The node uniform.
  31134. */
  31135. constructor( nodeUniform ) {
  31136. super( nodeUniform.name, nodeUniform.value );
  31137. /**
  31138. * The node uniform.
  31139. *
  31140. * @type {NodeUniform}
  31141. */
  31142. this.nodeUniform = nodeUniform;
  31143. }
  31144. /**
  31145. * Overwritten to return the value of the node uniform.
  31146. *
  31147. * @return {Vector4} The value.
  31148. */
  31149. getValue() {
  31150. return this.nodeUniform.value;
  31151. }
  31152. /**
  31153. * Returns the node uniform data type.
  31154. *
  31155. * @return {string} The data type.
  31156. */
  31157. getType() {
  31158. return this.nodeUniform.type;
  31159. }
  31160. }
  31161. /**
  31162. * A special form of Color uniform binding type.
  31163. * It's value is managed by a node object.
  31164. *
  31165. * @private
  31166. * @augments ColorUniform
  31167. */
  31168. class ColorNodeUniform extends ColorUniform {
  31169. /**
  31170. * Constructs a new node-based Color uniform.
  31171. *
  31172. * @param {NodeUniform} nodeUniform - The node uniform.
  31173. */
  31174. constructor( nodeUniform ) {
  31175. super( nodeUniform.name, nodeUniform.value );
  31176. /**
  31177. * The node uniform.
  31178. *
  31179. * @type {NodeUniform}
  31180. */
  31181. this.nodeUniform = nodeUniform;
  31182. }
  31183. /**
  31184. * Overwritten to return the value of the node uniform.
  31185. *
  31186. * @return {Color} The value.
  31187. */
  31188. getValue() {
  31189. return this.nodeUniform.value;
  31190. }
  31191. /**
  31192. * Returns the node uniform data type.
  31193. *
  31194. * @return {string} The data type.
  31195. */
  31196. getType() {
  31197. return this.nodeUniform.type;
  31198. }
  31199. }
  31200. /**
  31201. * A special form of Matrix2 uniform binding type.
  31202. * It's value is managed by a node object.
  31203. *
  31204. * @private
  31205. * @augments Matrix2Uniform
  31206. */
  31207. class Matrix2NodeUniform extends Matrix2Uniform {
  31208. /**
  31209. * Constructs a new node-based Matrix2 uniform.
  31210. *
  31211. * @param {NodeUniform} nodeUniform - The node uniform.
  31212. */
  31213. constructor( nodeUniform ) {
  31214. super( nodeUniform.name, nodeUniform.value );
  31215. /**
  31216. * The node uniform.
  31217. *
  31218. * @type {NodeUniform}
  31219. */
  31220. this.nodeUniform = nodeUniform;
  31221. }
  31222. /**
  31223. * Overwritten to return the value of the node uniform.
  31224. *
  31225. * @return {Matrix2} The value.
  31226. */
  31227. getValue() {
  31228. return this.nodeUniform.value;
  31229. }
  31230. /**
  31231. * Returns the node uniform data type.
  31232. *
  31233. * @return {string} The data type.
  31234. */
  31235. getType() {
  31236. return this.nodeUniform.type;
  31237. }
  31238. }
  31239. /**
  31240. * A special form of Matrix3 uniform binding type.
  31241. * It's value is managed by a node object.
  31242. *
  31243. * @private
  31244. * @augments Matrix3Uniform
  31245. */
  31246. class Matrix3NodeUniform extends Matrix3Uniform {
  31247. /**
  31248. * Constructs a new node-based Matrix3 uniform.
  31249. *
  31250. * @param {NodeUniform} nodeUniform - The node uniform.
  31251. */
  31252. constructor( nodeUniform ) {
  31253. super( nodeUniform.name, nodeUniform.value );
  31254. /**
  31255. * The node uniform.
  31256. *
  31257. * @type {NodeUniform}
  31258. */
  31259. this.nodeUniform = nodeUniform;
  31260. }
  31261. /**
  31262. * Overwritten to return the value of the node uniform.
  31263. *
  31264. * @return {Matrix3} The value.
  31265. */
  31266. getValue() {
  31267. return this.nodeUniform.value;
  31268. }
  31269. /**
  31270. * Returns the node uniform data type.
  31271. *
  31272. * @return {string} The data type.
  31273. */
  31274. getType() {
  31275. return this.nodeUniform.type;
  31276. }
  31277. }
  31278. /**
  31279. * A special form of Matrix4 uniform binding type.
  31280. * It's value is managed by a node object.
  31281. *
  31282. * @private
  31283. * @augments Matrix4Uniform
  31284. */
  31285. class Matrix4NodeUniform extends Matrix4Uniform {
  31286. /**
  31287. * Constructs a new node-based Matrix4 uniform.
  31288. *
  31289. * @param {NodeUniform} nodeUniform - The node uniform.
  31290. */
  31291. constructor( nodeUniform ) {
  31292. super( nodeUniform.name, nodeUniform.value );
  31293. /**
  31294. * The node uniform.
  31295. *
  31296. * @type {NodeUniform}
  31297. */
  31298. this.nodeUniform = nodeUniform;
  31299. }
  31300. /**
  31301. * Overwritten to return the value of the node uniform.
  31302. *
  31303. * @return {Matrix4} The value.
  31304. */
  31305. getValue() {
  31306. return this.nodeUniform.value;
  31307. }
  31308. /**
  31309. * Returns the node uniform data type.
  31310. *
  31311. * @return {string} The data type.
  31312. */
  31313. getType() {
  31314. return this.nodeUniform.type;
  31315. }
  31316. }
  31317. const rendererCache = new WeakMap();
  31318. const typeFromArray = new Map( [
  31319. [ Int8Array, 'int' ],
  31320. [ Int16Array, 'int' ],
  31321. [ Int32Array, 'int' ],
  31322. [ Uint8Array, 'uint' ],
  31323. [ Uint16Array, 'uint' ],
  31324. [ Uint32Array, 'uint' ],
  31325. [ Float32Array, 'float' ]
  31326. ] );
  31327. const toFloat = ( value ) => {
  31328. if ( /e/g.test( value ) ) {
  31329. return String( value ).replace( /\+/g, '' );
  31330. } else {
  31331. value = Number( value );
  31332. return value + ( value % 1 ? '' : '.0' );
  31333. }
  31334. };
  31335. /**
  31336. * Base class for builders which generate a shader program based
  31337. * on a 3D object and its node material definition.
  31338. */
  31339. class NodeBuilder {
  31340. /**
  31341. * Constructs a new node builder.
  31342. *
  31343. * @param {Object3D} object - The 3D object.
  31344. * @param {Renderer} renderer - The current renderer.
  31345. * @param {NodeParser} parser - A reference to a node parser.
  31346. */
  31347. constructor( object, renderer, parser ) {
  31348. /**
  31349. * The 3D object.
  31350. *
  31351. * @type {Object3D}
  31352. */
  31353. this.object = object;
  31354. /**
  31355. * The material of the 3D object.
  31356. *
  31357. * @type {?Material}
  31358. */
  31359. this.material = ( object && object.material ) || null;
  31360. /**
  31361. * The geometry of the 3D object.
  31362. *
  31363. * @type {?BufferGeometry}
  31364. */
  31365. this.geometry = ( object && object.geometry ) || null;
  31366. /**
  31367. * The current renderer.
  31368. *
  31369. * @type {Renderer}
  31370. */
  31371. this.renderer = renderer;
  31372. /**
  31373. * A reference to a node parser.
  31374. *
  31375. * @type {NodeParser}
  31376. */
  31377. this.parser = parser;
  31378. /**
  31379. * The scene the 3D object belongs to.
  31380. *
  31381. * @type {?Scene}
  31382. * @default null
  31383. */
  31384. this.scene = null;
  31385. /**
  31386. * The camera the 3D object is rendered with.
  31387. *
  31388. * @type {?Camera}
  31389. * @default null
  31390. */
  31391. this.camera = null;
  31392. /**
  31393. * A list of all nodes the builder is processing
  31394. * for this 3D object.
  31395. *
  31396. * @type {Array<Node>}
  31397. */
  31398. this.nodes = [];
  31399. /**
  31400. * A list of all sequential nodes.
  31401. *
  31402. * @type {Array<Node>}
  31403. */
  31404. this.sequentialNodes = [];
  31405. /**
  31406. * A list of all nodes which {@link Node#update} method should be executed.
  31407. *
  31408. * @type {Array<Node>}
  31409. */
  31410. this.updateNodes = [];
  31411. /**
  31412. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  31413. *
  31414. * @type {Array<Node>}
  31415. */
  31416. this.updateBeforeNodes = [];
  31417. /**
  31418. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  31419. *
  31420. * @type {Array<Node>}
  31421. */
  31422. this.updateAfterNodes = [];
  31423. /**
  31424. * A dictionary that assigns each node to a unique hash.
  31425. *
  31426. * @type {Object<number,Node>}
  31427. */
  31428. this.hashNodes = {};
  31429. /**
  31430. * A reference to a node material observer.
  31431. *
  31432. * @type {?NodeMaterialObserver}
  31433. * @default null
  31434. */
  31435. this.observer = null;
  31436. /**
  31437. * A reference to the current lights node.
  31438. *
  31439. * @type {?LightsNode}
  31440. * @default null
  31441. */
  31442. this.lightsNode = null;
  31443. /**
  31444. * A reference to the current environment node.
  31445. *
  31446. * @type {?Node}
  31447. * @default null
  31448. */
  31449. this.environmentNode = null;
  31450. /**
  31451. * A reference to the current fog node.
  31452. *
  31453. * @type {?FogNode}
  31454. * @default null
  31455. */
  31456. this.fogNode = null;
  31457. /**
  31458. * The current clipping context.
  31459. *
  31460. * @type {?ClippingContext}
  31461. */
  31462. this.clippingContext = null;
  31463. /**
  31464. * The generated vertex shader.
  31465. *
  31466. * @type {?string}
  31467. */
  31468. this.vertexShader = null;
  31469. /**
  31470. * The generated fragment shader.
  31471. *
  31472. * @type {?string}
  31473. */
  31474. this.fragmentShader = null;
  31475. /**
  31476. * The generated compute shader.
  31477. *
  31478. * @type {?string}
  31479. */
  31480. this.computeShader = null;
  31481. /**
  31482. * Nodes used in the primary flow of code generation.
  31483. *
  31484. * @type {Object<string,Array<Node>>}
  31485. */
  31486. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  31487. /**
  31488. * Nodes code from `.flowNodes`.
  31489. *
  31490. * @type {Object<string,string>}
  31491. */
  31492. this.flowCode = { vertex: '', fragment: '', compute: '' };
  31493. /**
  31494. * This dictionary holds the node uniforms of the builder.
  31495. * The uniforms are maintained in an array for each shader stage.
  31496. *
  31497. * @type {Object}
  31498. */
  31499. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  31500. /**
  31501. * This dictionary holds the output structs of the builder.
  31502. * The structs are maintained in an array for each shader stage.
  31503. *
  31504. * @type {Object}
  31505. */
  31506. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  31507. /**
  31508. * This dictionary holds the bindings for each shader stage.
  31509. *
  31510. * @type {Object}
  31511. */
  31512. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  31513. /**
  31514. * This dictionary maintains the binding indices per bind group.
  31515. *
  31516. * @type {Object}
  31517. */
  31518. this.bindingsIndexes = {};
  31519. /**
  31520. * Reference to the array of bind groups.
  31521. *
  31522. * @type {?Array<BindGroup>}
  31523. */
  31524. this.bindGroups = null;
  31525. /**
  31526. * This array holds the node attributes of this builder
  31527. * created via {@link AttributeNode}.
  31528. *
  31529. * @type {Array<NodeAttribute>}
  31530. */
  31531. this.attributes = [];
  31532. /**
  31533. * This array holds the node attributes of this builder
  31534. * created via {@link BufferAttributeNode}.
  31535. *
  31536. * @type {Array<NodeAttribute>}
  31537. */
  31538. this.bufferAttributes = [];
  31539. /**
  31540. * This array holds the node varyings of this builder.
  31541. *
  31542. * @type {Array<NodeVarying>}
  31543. */
  31544. this.varyings = [];
  31545. /**
  31546. * This dictionary holds the (native) node codes of this builder.
  31547. * The codes are maintained in an array for each shader stage.
  31548. *
  31549. * @type {Object<string,Array<NodeCode>>}
  31550. */
  31551. this.codes = {};
  31552. /**
  31553. * This dictionary holds the node variables of this builder.
  31554. * The variables are maintained in an array for each shader stage.
  31555. * This dictionary is also used to count the number of variables
  31556. * according to their type (const, vars).
  31557. *
  31558. * @type {Object<string,Array<NodeVar>|number>}
  31559. */
  31560. this.vars = {};
  31561. /**
  31562. * This dictionary holds the declarations for each shader stage.
  31563. *
  31564. * @type {Object}
  31565. */
  31566. this.declarations = {};
  31567. /**
  31568. * Current code flow.
  31569. * All code generated in this stack will be stored in `.flow`.
  31570. *
  31571. * @type {{code: string}}
  31572. */
  31573. this.flow = { code: '' };
  31574. /**
  31575. * A chain of nodes.
  31576. * Used to check recursive calls in node-graph.
  31577. *
  31578. * @type {Array<Node>}
  31579. */
  31580. this.chaining = [];
  31581. /**
  31582. * The current stack.
  31583. * This reflects the current process in the code block hierarchy,
  31584. * it is useful to know if the current process is inside a conditional for example.
  31585. *
  31586. * @type {StackNode}
  31587. */
  31588. this.stack = stack();
  31589. /**
  31590. * List of stack nodes.
  31591. * The current stack hierarchy is stored in an array.
  31592. *
  31593. * @type {Array<StackNode>}
  31594. */
  31595. this.stacks = [];
  31596. /**
  31597. * A tab value. Used for shader string generation.
  31598. *
  31599. * @type {string}
  31600. * @default '\t'
  31601. */
  31602. this.tab = '\t';
  31603. /**
  31604. * Reference to the current function node.
  31605. *
  31606. * @type {?FunctionNode}
  31607. * @default null
  31608. */
  31609. this.currentFunctionNode = null;
  31610. /**
  31611. * The builder's context.
  31612. *
  31613. * @type {Object}
  31614. */
  31615. this.context = {
  31616. material: this.material
  31617. };
  31618. /**
  31619. * The builder's cache.
  31620. *
  31621. * @type {NodeCache}
  31622. */
  31623. this.cache = new NodeCache();
  31624. /**
  31625. * Since the {@link NodeBuilder#cache} might be temporarily
  31626. * overwritten by other caches, this member retains the reference
  31627. * to the builder's own cache.
  31628. *
  31629. * @type {NodeCache}
  31630. * @default this.cache
  31631. */
  31632. this.globalCache = this.cache;
  31633. this.flowsData = new WeakMap();
  31634. /**
  31635. * The current shader stage.
  31636. *
  31637. * @type {?('vertex'|'fragment'|'compute'|'any')}
  31638. */
  31639. this.shaderStage = null;
  31640. /**
  31641. * The current build stage.
  31642. *
  31643. * @type {?('setup'|'analyze'|'generate')}
  31644. */
  31645. this.buildStage = null;
  31646. }
  31647. /**
  31648. * Returns the bind groups of the current renderer.
  31649. *
  31650. * @return {ChainMap} The cache.
  31651. */
  31652. getBindGroupsCache() {
  31653. let bindGroupsCache = rendererCache.get( this.renderer );
  31654. if ( bindGroupsCache === undefined ) {
  31655. bindGroupsCache = new ChainMap();
  31656. rendererCache.set( this.renderer, bindGroupsCache );
  31657. }
  31658. return bindGroupsCache;
  31659. }
  31660. /**
  31661. * Factory method for creating an instance of {@link RenderTarget} with the given
  31662. * dimensions and options.
  31663. *
  31664. * @param {number} width - The width of the render target.
  31665. * @param {number} height - The height of the render target.
  31666. * @param {Object} options - The options of the render target.
  31667. * @return {RenderTarget} The render target.
  31668. */
  31669. createRenderTarget( width, height, options ) {
  31670. return new RenderTarget( width, height, options );
  31671. }
  31672. /**
  31673. * Factory method for creating an instance of {@link RenderTargetArray} with the given
  31674. * dimensions and options.
  31675. *
  31676. * @param {number} width - The width of the render target.
  31677. * @param {number} height - The height of the render target.
  31678. * @param {number} depth - The depth of the render target.
  31679. * @param {Object} options - The options of the render target.
  31680. * @return {RenderTargetArray} The render target.
  31681. */
  31682. createRenderTargetArray( width, height, depth, options ) {
  31683. return new RenderTargetArray( width, height, depth, options );
  31684. }
  31685. /**
  31686. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  31687. * dimensions and options.
  31688. *
  31689. * @param {number} size - The size of the cube render target.
  31690. * @param {Object} options - The options of the cube render target.
  31691. * @return {CubeRenderTarget} The cube render target.
  31692. */
  31693. createCubeRenderTarget( size, options ) {
  31694. return new CubeRenderTarget( size, options );
  31695. }
  31696. /**
  31697. * Whether the given node is included in the internal array of nodes or not.
  31698. *
  31699. * @param {Node} node - The node to test.
  31700. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  31701. */
  31702. includes( node ) {
  31703. return this.nodes.includes( node );
  31704. }
  31705. /**
  31706. * Returns the output struct name which is required by
  31707. * {@link OutputStructNode}.
  31708. *
  31709. * @abstract
  31710. * @return {string} The name of the output struct.
  31711. */
  31712. getOutputStructName() {}
  31713. /**
  31714. * Returns a bind group for the given group name and binding.
  31715. *
  31716. * @private
  31717. * @param {string} groupName - The group name.
  31718. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  31719. * @return {BindGroup} The bind group
  31720. */
  31721. _getBindGroup( groupName, bindings ) {
  31722. const bindGroupsCache = this.getBindGroupsCache();
  31723. //
  31724. const bindingsArray = [];
  31725. let sharedGroup = true;
  31726. for ( const binding of bindings ) {
  31727. bindingsArray.push( binding );
  31728. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  31729. }
  31730. //
  31731. let bindGroup;
  31732. if ( sharedGroup ) {
  31733. bindGroup = bindGroupsCache.get( bindingsArray );
  31734. if ( bindGroup === undefined ) {
  31735. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31736. bindGroupsCache.set( bindingsArray, bindGroup );
  31737. }
  31738. } else {
  31739. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  31740. }
  31741. return bindGroup;
  31742. }
  31743. /**
  31744. * Returns an array of node uniform groups for the given group name and shader stage.
  31745. *
  31746. * @param {string} groupName - The group name.
  31747. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31748. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  31749. */
  31750. getBindGroupArray( groupName, shaderStage ) {
  31751. const bindings = this.bindings[ shaderStage ];
  31752. let bindGroup = bindings[ groupName ];
  31753. if ( bindGroup === undefined ) {
  31754. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  31755. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  31756. }
  31757. bindings[ groupName ] = bindGroup = [];
  31758. }
  31759. return bindGroup;
  31760. }
  31761. /**
  31762. * Returns a list bindings of all shader stages separated by groups.
  31763. *
  31764. * @return {Array<BindGroup>} The list of bindings.
  31765. */
  31766. getBindings() {
  31767. let bindingsGroups = this.bindGroups;
  31768. if ( bindingsGroups === null ) {
  31769. const groups = {};
  31770. const bindings = this.bindings;
  31771. for ( const shaderStage of shaderStages ) {
  31772. for ( const groupName in bindings[ shaderStage ] ) {
  31773. const uniforms = bindings[ shaderStage ][ groupName ];
  31774. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  31775. groupUniforms.push( ...uniforms );
  31776. }
  31777. }
  31778. bindingsGroups = [];
  31779. for ( const groupName in groups ) {
  31780. const group = groups[ groupName ];
  31781. const bindingsGroup = this._getBindGroup( groupName, group );
  31782. bindingsGroups.push( bindingsGroup );
  31783. }
  31784. this.bindGroups = bindingsGroups;
  31785. }
  31786. return bindingsGroups;
  31787. }
  31788. /**
  31789. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  31790. */
  31791. sortBindingGroups() {
  31792. const bindingsGroups = this.getBindings();
  31793. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  31794. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  31795. const bindingGroup = bindingsGroups[ i ];
  31796. this.bindingsIndexes[ bindingGroup.name ].group = i;
  31797. bindingGroup.index = i;
  31798. }
  31799. }
  31800. /**
  31801. * The builder maintains each node in a hash-based dictionary.
  31802. * This method sets the given node (value) with the given hash (key) into this dictionary.
  31803. *
  31804. * @param {Node} node - The node to add.
  31805. * @param {number} hash - The hash of the node.
  31806. */
  31807. setHashNode( node, hash ) {
  31808. this.hashNodes[ hash ] = node;
  31809. }
  31810. /**
  31811. * Adds a node to this builder.
  31812. *
  31813. * @param {Node} node - The node to add.
  31814. */
  31815. addNode( node ) {
  31816. if ( this.nodes.includes( node ) === false ) {
  31817. this.nodes.push( node );
  31818. this.setHashNode( node, node.getHash( this ) );
  31819. }
  31820. }
  31821. /**
  31822. * It is used to add Nodes that will be used as FRAME and RENDER events,
  31823. * and need to follow a certain sequence in the calls to work correctly.
  31824. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  31825. *
  31826. * @param {Node} node - The node to add.
  31827. */
  31828. addSequentialNode( node ) {
  31829. if ( this.sequentialNodes.includes( node ) === false ) {
  31830. this.sequentialNodes.push( node );
  31831. }
  31832. }
  31833. /**
  31834. * Checks the update types of nodes
  31835. */
  31836. buildUpdateNodes() {
  31837. for ( const node of this.nodes ) {
  31838. const updateType = node.getUpdateType();
  31839. if ( updateType !== NodeUpdateType.NONE ) {
  31840. this.updateNodes.push( node.getSelf() );
  31841. }
  31842. }
  31843. for ( const node of this.sequentialNodes ) {
  31844. const updateBeforeType = node.getUpdateBeforeType();
  31845. const updateAfterType = node.getUpdateAfterType();
  31846. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  31847. this.updateBeforeNodes.push( node.getSelf() );
  31848. }
  31849. if ( updateAfterType !== NodeUpdateType.NONE ) {
  31850. this.updateAfterNodes.push( node.getSelf() );
  31851. }
  31852. }
  31853. }
  31854. /**
  31855. * A reference the current node which is the
  31856. * last node in the chain of nodes.
  31857. *
  31858. * @type {Node}
  31859. */
  31860. get currentNode() {
  31861. return this.chaining[ this.chaining.length - 1 ];
  31862. }
  31863. /**
  31864. * Whether the given texture is filtered or not.
  31865. *
  31866. * @param {Texture} texture - The texture to check.
  31867. * @return {boolean} Whether the given texture is filtered or not.
  31868. */
  31869. isFilteredTexture( texture ) {
  31870. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  31871. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  31872. }
  31873. /**
  31874. * Adds the given node to the internal node chain.
  31875. * This is used to check recursive calls in node-graph.
  31876. *
  31877. * @param {Node} node - The node to add.
  31878. */
  31879. addChain( node ) {
  31880. /*
  31881. if ( this.chaining.indexOf( node ) !== - 1 ) {
  31882. console.warn( 'Recursive node: ', node );
  31883. }
  31884. */
  31885. this.chaining.push( node );
  31886. }
  31887. /**
  31888. * Removes the given node from the internal node chain.
  31889. *
  31890. * @param {Node} node - The node to remove.
  31891. */
  31892. removeChain( node ) {
  31893. const lastChain = this.chaining.pop();
  31894. if ( lastChain !== node ) {
  31895. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  31896. }
  31897. }
  31898. /**
  31899. * Returns the native shader method name for a given generic name. E.g.
  31900. * the method name `textureDimensions` matches the WGSL name but must be
  31901. * resolved to `textureSize` in GLSL.
  31902. *
  31903. * @abstract
  31904. * @param {string} method - The method name to resolve.
  31905. * @return {string} The resolved method name.
  31906. */
  31907. getMethod( method ) {
  31908. return method;
  31909. }
  31910. /**
  31911. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  31912. *
  31913. * @param {number} hash - The hash of the node.
  31914. * @return {Node} The found node.
  31915. */
  31916. getNodeFromHash( hash ) {
  31917. return this.hashNodes[ hash ];
  31918. }
  31919. /**
  31920. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  31921. *
  31922. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  31923. * @param {Node} node - The node to add.
  31924. * @return {Node} The node.
  31925. */
  31926. addFlow( shaderStage, node ) {
  31927. this.flowNodes[ shaderStage ].push( node );
  31928. return node;
  31929. }
  31930. /**
  31931. * Sets builder's context.
  31932. *
  31933. * @param {Object} context - The context to set.
  31934. */
  31935. setContext( context ) {
  31936. this.context = context;
  31937. }
  31938. /**
  31939. * Returns the builder's current context.
  31940. *
  31941. * @return {Object} The builder's current context.
  31942. */
  31943. getContext() {
  31944. return this.context;
  31945. }
  31946. /**
  31947. * Gets a context used in shader construction that can be shared across different materials.
  31948. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  31949. *
  31950. * @return {Object} The builder's current context without material.
  31951. */
  31952. getSharedContext() {
  31953. ({ ...this.context });
  31954. return this.context;
  31955. }
  31956. /**
  31957. * Sets builder's cache.
  31958. *
  31959. * @param {NodeCache} cache - The cache to set.
  31960. */
  31961. setCache( cache ) {
  31962. this.cache = cache;
  31963. }
  31964. /**
  31965. * Returns the builder's current cache.
  31966. *
  31967. * @return {NodeCache} The builder's current cache.
  31968. */
  31969. getCache() {
  31970. return this.cache;
  31971. }
  31972. /**
  31973. * Returns a cache for the given node.
  31974. *
  31975. * @param {Node} node - The node.
  31976. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  31977. * @return {NodeCache} The cache.
  31978. */
  31979. getCacheFromNode( node, parent = true ) {
  31980. const data = this.getDataFromNode( node );
  31981. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  31982. return data.cache;
  31983. }
  31984. /**
  31985. * Whether the requested feature is available or not.
  31986. *
  31987. * @abstract
  31988. * @param {string} name - The requested feature.
  31989. * @return {boolean} Whether the requested feature is supported or not.
  31990. */
  31991. isAvailable( /*name*/ ) {
  31992. return false;
  31993. }
  31994. /**
  31995. * Returns the vertexIndex input variable as a native shader string.
  31996. *
  31997. * @abstract
  31998. * @return {string} The instanceIndex shader string.
  31999. */
  32000. getVertexIndex() {
  32001. console.warn( 'Abstract function.' );
  32002. }
  32003. /**
  32004. * Returns the instanceIndex input variable as a native shader string.
  32005. *
  32006. * @abstract
  32007. * @return {string} The instanceIndex shader string.
  32008. */
  32009. getInstanceIndex() {
  32010. console.warn( 'Abstract function.' );
  32011. }
  32012. /**
  32013. * Returns the drawIndex input variable as a native shader string.
  32014. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  32015. *
  32016. * @abstract
  32017. * @return {?string} The drawIndex shader string.
  32018. */
  32019. getDrawIndex() {
  32020. console.warn( 'Abstract function.' );
  32021. }
  32022. /**
  32023. * Returns the frontFacing input variable as a native shader string.
  32024. *
  32025. * @abstract
  32026. * @return {string} The frontFacing shader string.
  32027. */
  32028. getFrontFacing() {
  32029. console.warn( 'Abstract function.' );
  32030. }
  32031. /**
  32032. * Returns the fragCoord input variable as a native shader string.
  32033. *
  32034. * @abstract
  32035. * @return {string} The fragCoord shader string.
  32036. */
  32037. getFragCoord() {
  32038. console.warn( 'Abstract function.' );
  32039. }
  32040. /**
  32041. * Whether to flip texture data along its vertical axis or not. WebGL needs
  32042. * this method evaluate to `true`, WebGPU to `false`.
  32043. *
  32044. * @abstract
  32045. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  32046. */
  32047. isFlipY() {
  32048. return false;
  32049. }
  32050. /**
  32051. * Calling this method increases the usage count for the given node by one.
  32052. *
  32053. * @param {Node} node - The node to increase the usage count for.
  32054. * @return {number} The updated usage count.
  32055. */
  32056. increaseUsage( node ) {
  32057. const nodeData = this.getDataFromNode( node );
  32058. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  32059. return nodeData.usageCount;
  32060. }
  32061. /**
  32062. * Generates a texture sample shader string for the given texture data.
  32063. *
  32064. * @abstract
  32065. * @param {Texture} texture - The texture.
  32066. * @param {string} textureProperty - The texture property name.
  32067. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32068. * @return {string} The generated shader string.
  32069. */
  32070. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  32071. console.warn( 'Abstract function.' );
  32072. }
  32073. /**
  32074. * Generates a texture LOD shader string for the given texture data.
  32075. *
  32076. * @abstract
  32077. * @param {Texture} texture - The texture.
  32078. * @param {string} textureProperty - The texture property name.
  32079. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32080. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  32081. * @param {string} levelSnippet - Snippet defining the mip level.
  32082. * @return {string} The generated shader string.
  32083. */
  32084. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  32085. console.warn( 'Abstract function.' );
  32086. }
  32087. /**
  32088. * Generates the array declaration string.
  32089. *
  32090. * @param {string} type - The type.
  32091. * @param {?number} [count] - The count.
  32092. * @return {string} The generated value as a shader string.
  32093. */
  32094. generateArrayDeclaration( type, count ) {
  32095. return this.getType( type ) + '[ ' + count + ' ]';
  32096. }
  32097. /**
  32098. * Generates the array shader string for the given type and value.
  32099. *
  32100. * @param {string} type - The type.
  32101. * @param {?number} [count] - The count.
  32102. * @param {?Array<Node>} [values=null] - The default values.
  32103. * @return {string} The generated value as a shader string.
  32104. */
  32105. generateArray( type, count, values = null ) {
  32106. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  32107. for ( let i = 0; i < count; i ++ ) {
  32108. const value = values ? values[ i ] : null;
  32109. if ( value !== null ) {
  32110. snippet += value.build( this, type );
  32111. } else {
  32112. snippet += this.generateConst( type );
  32113. }
  32114. if ( i < count - 1 ) snippet += ', ';
  32115. }
  32116. snippet += ' )';
  32117. return snippet;
  32118. }
  32119. /**
  32120. * Generates the struct shader string.
  32121. *
  32122. * @param {string} type - The type.
  32123. * @param {Array<Object>} [membersLayout] - The count.
  32124. * @param {?Array<Node>} [values=null] - The default values.
  32125. * @return {string} The generated value as a shader string.
  32126. */
  32127. generateStruct( type, membersLayout, values = null ) {
  32128. const snippets = [];
  32129. for ( const member of membersLayout ) {
  32130. const { name, type } = member;
  32131. if ( values && values[ name ] && values[ name ].isNode ) {
  32132. snippets.push( values[ name ].build( this, type ) );
  32133. } else {
  32134. snippets.push( this.generateConst( type ) );
  32135. }
  32136. }
  32137. return type + '( ' + snippets.join( ', ' ) + ' )';
  32138. }
  32139. /**
  32140. * Generates the shader string for the given type and value.
  32141. *
  32142. * @param {string} type - The type.
  32143. * @param {?any} [value=null] - The value.
  32144. * @return {string} The generated value as a shader string.
  32145. */
  32146. generateConst( type, value = null ) {
  32147. if ( value === null ) {
  32148. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  32149. else if ( type === 'bool' ) value = false;
  32150. else if ( type === 'color' ) value = new Color();
  32151. else if ( type === 'vec2' ) value = new Vector2();
  32152. else if ( type === 'vec3' ) value = new Vector3();
  32153. else if ( type === 'vec4' ) value = new Vector4();
  32154. }
  32155. if ( type === 'float' ) return toFloat( value );
  32156. if ( type === 'int' ) return `${ Math.round( value ) }`;
  32157. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  32158. if ( type === 'bool' ) return value ? 'true' : 'false';
  32159. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  32160. const typeLength = this.getTypeLength( type );
  32161. const componentType = this.getComponentType( type );
  32162. const generateConst = value => this.generateConst( componentType, value );
  32163. if ( typeLength === 2 ) {
  32164. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  32165. } else if ( typeLength === 3 ) {
  32166. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  32167. } else if ( typeLength === 4 && type !== 'mat2' ) {
  32168. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  32169. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  32170. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  32171. } else if ( typeLength > 4 ) {
  32172. return `${ this.getType( type ) }()`;
  32173. }
  32174. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  32175. }
  32176. /**
  32177. * It might be necessary to convert certain data types to different ones
  32178. * so this method can be used to hide the conversion.
  32179. *
  32180. * @param {string} type - The type.
  32181. * @return {string} The updated type.
  32182. */
  32183. getType( type ) {
  32184. if ( type === 'color' ) return 'vec3';
  32185. return type;
  32186. }
  32187. /**
  32188. * Whether the given attribute name is defined in the geometry or not.
  32189. *
  32190. * @param {string} name - The attribute name.
  32191. * @return {boolean} Whether the given attribute name is defined in the geometry.
  32192. */
  32193. hasGeometryAttribute( name ) {
  32194. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  32195. }
  32196. /**
  32197. * Returns a node attribute for the given name and type.
  32198. *
  32199. * @param {string} name - The attribute's name.
  32200. * @param {string} type - The attribute's type.
  32201. * @return {NodeAttribute} The node attribute.
  32202. */
  32203. getAttribute( name, type ) {
  32204. const attributes = this.attributes;
  32205. // find attribute
  32206. for ( const attribute of attributes ) {
  32207. if ( attribute.name === name ) {
  32208. return attribute;
  32209. }
  32210. }
  32211. // create a new if no exist
  32212. const attribute = new NodeAttribute( name, type );
  32213. this.registerDeclaration( attribute );
  32214. attributes.push( attribute );
  32215. return attribute;
  32216. }
  32217. /**
  32218. * Returns for the given node and shader stage the property name for the shader.
  32219. *
  32220. * @param {Node} node - The node.
  32221. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32222. * @return {string} The property name.
  32223. */
  32224. getPropertyName( node/*, shaderStage*/ ) {
  32225. return node.name;
  32226. }
  32227. /**
  32228. * Whether the given type is a vector type or not.
  32229. *
  32230. * @param {string} type - The type to check.
  32231. * @return {boolean} Whether the given type is a vector type or not.
  32232. */
  32233. isVector( type ) {
  32234. return /vec\d/.test( type );
  32235. }
  32236. /**
  32237. * Whether the given type is a matrix type or not.
  32238. *
  32239. * @param {string} type - The type to check.
  32240. * @return {boolean} Whether the given type is a matrix type or not.
  32241. */
  32242. isMatrix( type ) {
  32243. return /mat\d/.test( type );
  32244. }
  32245. /**
  32246. * Whether the given type is a reference type or not.
  32247. *
  32248. * @param {string} type - The type to check.
  32249. * @return {boolean} Whether the given type is a reference type or not.
  32250. */
  32251. isReference( type ) {
  32252. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  32253. }
  32254. /**
  32255. * Checks if the given texture requires a manual conversion to the working color space.
  32256. *
  32257. * @abstract
  32258. * @param {Texture} texture - The texture to check.
  32259. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  32260. */
  32261. needsToWorkingColorSpace( /*texture*/ ) {
  32262. return false;
  32263. }
  32264. /**
  32265. * Returns the component type of a given texture.
  32266. *
  32267. * @param {Texture} texture - The texture.
  32268. * @return {string} The component type.
  32269. */
  32270. getComponentTypeFromTexture( texture ) {
  32271. const type = texture.type;
  32272. if ( texture.isDataTexture ) {
  32273. if ( type === IntType ) return 'int';
  32274. if ( type === UnsignedIntType ) return 'uint';
  32275. }
  32276. return 'float';
  32277. }
  32278. /**
  32279. * Returns the element type for a given type.
  32280. *
  32281. * @param {string} type - The type.
  32282. * @return {string} The element type.
  32283. */
  32284. getElementType( type ) {
  32285. if ( type === 'mat2' ) return 'vec2';
  32286. if ( type === 'mat3' ) return 'vec3';
  32287. if ( type === 'mat4' ) return 'vec4';
  32288. return this.getComponentType( type );
  32289. }
  32290. /**
  32291. * Returns the component type for a given type.
  32292. *
  32293. * @param {string} type - The type.
  32294. * @return {string} The component type.
  32295. */
  32296. getComponentType( type ) {
  32297. type = this.getVectorType( type );
  32298. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  32299. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  32300. if ( componentType === null ) return null;
  32301. if ( componentType[ 1 ] === 'b' ) return 'bool';
  32302. if ( componentType[ 1 ] === 'i' ) return 'int';
  32303. if ( componentType[ 1 ] === 'u' ) return 'uint';
  32304. return 'float';
  32305. }
  32306. /**
  32307. * Returns the vector type for a given type.
  32308. *
  32309. * @param {string} type - The type.
  32310. * @return {string} The vector type.
  32311. */
  32312. getVectorType( type ) {
  32313. if ( type === 'color' ) return 'vec3';
  32314. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  32315. return type;
  32316. }
  32317. /**
  32318. * Returns the data type for the given the length and component type.
  32319. *
  32320. * @param {number} length - The length.
  32321. * @param {string} [componentType='float'] - The component type.
  32322. * @return {string} The type.
  32323. */
  32324. getTypeFromLength( length, componentType = 'float' ) {
  32325. if ( length === 1 ) return componentType;
  32326. let baseType = getTypeFromLength( length );
  32327. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  32328. // fix edge case for mat2x2 being same size as vec4
  32329. if ( /mat2/.test( componentType ) === true ) {
  32330. baseType = baseType.replace( 'vec', 'mat' );
  32331. }
  32332. return prefix + baseType;
  32333. }
  32334. /**
  32335. * Returns the type for a given typed array.
  32336. *
  32337. * @param {TypedArray} array - The typed array.
  32338. * @return {string} The type.
  32339. */
  32340. getTypeFromArray( array ) {
  32341. return typeFromArray.get( array.constructor );
  32342. }
  32343. /**
  32344. * Returns the type is an integer type.
  32345. *
  32346. * @param {string} type - The type.
  32347. * @return {boolean} Whether the type is an integer type or not.
  32348. */
  32349. isInteger( type ) {
  32350. return /int|uint|(i|u)vec/.test( type );
  32351. }
  32352. /**
  32353. * Returns the type for a given buffer attribute.
  32354. *
  32355. * @param {BufferAttribute} attribute - The buffer attribute.
  32356. * @return {string} The type.
  32357. */
  32358. getTypeFromAttribute( attribute ) {
  32359. let dataAttribute = attribute;
  32360. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  32361. const array = dataAttribute.array;
  32362. const itemSize = attribute.itemSize;
  32363. const normalized = attribute.normalized;
  32364. let arrayType;
  32365. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  32366. arrayType = this.getTypeFromArray( array );
  32367. }
  32368. return this.getTypeFromLength( itemSize, arrayType );
  32369. }
  32370. /**
  32371. * Returns the length for the given data type.
  32372. *
  32373. * @param {string} type - The data type.
  32374. * @return {number} The length.
  32375. */
  32376. getTypeLength( type ) {
  32377. const vecType = this.getVectorType( type );
  32378. const vecNum = /vec([2-4])/.exec( vecType );
  32379. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  32380. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  32381. if ( /mat2/.test( type ) === true ) return 4;
  32382. if ( /mat3/.test( type ) === true ) return 9;
  32383. if ( /mat4/.test( type ) === true ) return 16;
  32384. return 0;
  32385. }
  32386. /**
  32387. * Returns the vector type for a given matrix type.
  32388. *
  32389. * @param {string} type - The matrix type.
  32390. * @return {string} The vector type.
  32391. */
  32392. getVectorFromMatrix( type ) {
  32393. return type.replace( 'mat', 'vec' );
  32394. }
  32395. /**
  32396. * For a given type this method changes the component type to the
  32397. * given value. E.g. `vec4` should be changed to the new component type
  32398. * `uint` which results in `uvec4`.
  32399. *
  32400. * @param {string} type - The type.
  32401. * @param {string} newComponentType - The new component type.
  32402. * @return {string} The new type.
  32403. */
  32404. changeComponentType( type, newComponentType ) {
  32405. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  32406. }
  32407. /**
  32408. * Returns the integer type pendant for the given type.
  32409. *
  32410. * @param {string} type - The type.
  32411. * @return {string} The integer type.
  32412. */
  32413. getIntegerType( type ) {
  32414. const componentType = this.getComponentType( type );
  32415. if ( componentType === 'int' || componentType === 'uint' ) return type;
  32416. return this.changeComponentType( type, 'int' );
  32417. }
  32418. /**
  32419. * Adds a stack node to the internal stack.
  32420. *
  32421. * @return {StackNode} The added stack node.
  32422. */
  32423. addStack() {
  32424. this.stack = stack( this.stack );
  32425. this.stacks.push( getCurrentStack() || this.stack );
  32426. setCurrentStack( this.stack );
  32427. return this.stack;
  32428. }
  32429. /**
  32430. * Removes the last stack node from the internal stack.
  32431. *
  32432. * @return {StackNode} The removed stack node.
  32433. */
  32434. removeStack() {
  32435. const lastStack = this.stack;
  32436. this.stack = lastStack.parent;
  32437. setCurrentStack( this.stacks.pop() );
  32438. return lastStack;
  32439. }
  32440. /**
  32441. * The builder maintains (cached) data for each node during the building process. This method
  32442. * can be used to get these data for a specific shader stage and cache.
  32443. *
  32444. * @param {Node} node - The node to get the data for.
  32445. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32446. * @param {?NodeCache} cache - An optional cache.
  32447. * @return {Object} The node data.
  32448. */
  32449. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  32450. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  32451. let nodeData = cache.getData( node );
  32452. if ( nodeData === undefined ) {
  32453. nodeData = {};
  32454. cache.setData( node, nodeData );
  32455. }
  32456. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  32457. return nodeData[ shaderStage ];
  32458. }
  32459. /**
  32460. * Returns the properties for the given node and shader stage.
  32461. *
  32462. * @param {Node} node - The node to get the properties for.
  32463. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  32464. * @return {Object} The node properties.
  32465. */
  32466. getNodeProperties( node, shaderStage = 'any' ) {
  32467. const nodeData = this.getDataFromNode( node, shaderStage );
  32468. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  32469. }
  32470. /**
  32471. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  32472. *
  32473. * @param {BufferAttributeNode} node - The buffer attribute node.
  32474. * @param {string} type - The node type.
  32475. * @return {NodeAttribute} The node attribute.
  32476. */
  32477. getBufferAttributeFromNode( node, type ) {
  32478. const nodeData = this.getDataFromNode( node );
  32479. let bufferAttribute = nodeData.bufferAttribute;
  32480. if ( bufferAttribute === undefined ) {
  32481. const index = this.uniforms.index ++;
  32482. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  32483. this.bufferAttributes.push( bufferAttribute );
  32484. nodeData.bufferAttribute = bufferAttribute;
  32485. }
  32486. return bufferAttribute;
  32487. }
  32488. /**
  32489. * Returns an instance of {@link StructType} for the given output struct node.
  32490. *
  32491. * @param {OutputStructNode} node - The output struct node.
  32492. * @param {Array<Object>} membersLayout - The output struct types.
  32493. * @param {?string} [name=null] - The name of the struct.
  32494. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32495. * @return {StructType} The struct type attribute.
  32496. */
  32497. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  32498. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32499. let structType = nodeData.structType;
  32500. if ( structType === undefined ) {
  32501. const index = this.structs.index ++;
  32502. if ( name === null ) name = 'StructType' + index;
  32503. structType = new StructType( name, membersLayout );
  32504. this.structs[ shaderStage ].push( structType );
  32505. nodeData.structType = structType;
  32506. }
  32507. return structType;
  32508. }
  32509. /**
  32510. * Returns an instance of {@link StructType} for the given output struct node.
  32511. *
  32512. * @param {OutputStructNode} node - The output struct node.
  32513. * @param {Array<Object>} membersLayout - The output struct types.
  32514. * @return {StructType} The struct type attribute.
  32515. */
  32516. getOutputStructTypeFromNode( node, membersLayout ) {
  32517. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  32518. structType.output = true;
  32519. return structType;
  32520. }
  32521. /**
  32522. * Returns an instance of {@link NodeUniform} for the given uniform node.
  32523. *
  32524. * @param {UniformNode} node - The uniform node.
  32525. * @param {string} type - The uniform type.
  32526. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32527. * @param {?string} name - The name of the uniform.
  32528. * @return {NodeUniform} The node uniform.
  32529. */
  32530. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  32531. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32532. let nodeUniform = nodeData.uniform;
  32533. if ( nodeUniform === undefined ) {
  32534. const index = this.uniforms.index ++;
  32535. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  32536. this.uniforms[ shaderStage ].push( nodeUniform );
  32537. this.registerDeclaration( nodeUniform );
  32538. nodeData.uniform = nodeUniform;
  32539. }
  32540. return nodeUniform;
  32541. }
  32542. /**
  32543. * Returns the array length.
  32544. *
  32545. * @param {Node} node - The node.
  32546. * @return {?number} The array length.
  32547. */
  32548. getArrayCount( node ) {
  32549. let count = null;
  32550. if ( node.isArrayNode ) count = node.count;
  32551. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  32552. return count;
  32553. }
  32554. /**
  32555. * Returns an instance of {@link NodeVar} for the given variable node.
  32556. *
  32557. * @param {VarNode} node - The variable node.
  32558. * @param {?string} name - The variable's name.
  32559. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  32560. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32561. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  32562. *
  32563. * @return {NodeVar} The node variable.
  32564. */
  32565. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  32566. const nodeData = this.getDataFromNode( node, shaderStage );
  32567. let nodeVar = nodeData.variable;
  32568. if ( nodeVar === undefined ) {
  32569. const idNS = readOnly ? '_const' : '_var';
  32570. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  32571. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  32572. if ( name === null ) {
  32573. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  32574. this.vars[ idNS ] ++;
  32575. }
  32576. //
  32577. const count = this.getArrayCount( node );
  32578. nodeVar = new NodeVar( name, type, readOnly, count );
  32579. if ( ! readOnly ) {
  32580. vars.push( nodeVar );
  32581. }
  32582. this.registerDeclaration( nodeVar );
  32583. nodeData.variable = nodeVar;
  32584. }
  32585. return nodeVar;
  32586. }
  32587. /**
  32588. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  32589. *
  32590. * @param {Node} node - The varying node.
  32591. * @return {boolean} Returns true if deterministic.
  32592. */
  32593. isDeterministic( node ) {
  32594. if ( node.isMathNode ) {
  32595. return this.isDeterministic( node.aNode ) &&
  32596. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  32597. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  32598. } else if ( node.isOperatorNode ) {
  32599. return this.isDeterministic( node.aNode ) &&
  32600. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  32601. } else if ( node.isArrayNode ) {
  32602. if ( node.values !== null ) {
  32603. for ( const n of node.values ) {
  32604. if ( ! this.isDeterministic( n ) ) {
  32605. return false;
  32606. }
  32607. }
  32608. }
  32609. return true;
  32610. } else if ( node.isConstNode ) {
  32611. return true;
  32612. }
  32613. return false;
  32614. }
  32615. /**
  32616. * Returns an instance of {@link NodeVarying} for the given varying node.
  32617. *
  32618. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  32619. * @param {?string} name - The varying's name.
  32620. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  32621. * @param {?string} interpolationType - The interpolation type of the varying.
  32622. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32623. * @return {NodeVar} The node varying.
  32624. */
  32625. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  32626. const nodeData = this.getDataFromNode( node, 'any' );
  32627. let nodeVarying = nodeData.varying;
  32628. if ( nodeVarying === undefined ) {
  32629. const varyings = this.varyings;
  32630. const index = varyings.length;
  32631. if ( name === null ) name = 'nodeVarying' + index;
  32632. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  32633. varyings.push( nodeVarying );
  32634. this.registerDeclaration( nodeVarying );
  32635. nodeData.varying = nodeVarying;
  32636. }
  32637. return nodeVarying;
  32638. }
  32639. /**
  32640. * Registers a node declaration in the current shader stage.
  32641. *
  32642. * @param {Object} node - The node to be registered.
  32643. */
  32644. registerDeclaration( node ) {
  32645. const shaderStage = this.shaderStage;
  32646. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  32647. const property = this.getPropertyName( node );
  32648. let index = 1;
  32649. let name = property;
  32650. // Automatically renames the property if the name is already in use.
  32651. while ( declarations[ name ] !== undefined ) {
  32652. name = property + '_' + index ++;
  32653. }
  32654. if ( index > 1 ) {
  32655. node.name = name;
  32656. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  32657. }
  32658. declarations[ name ] = node;
  32659. }
  32660. /**
  32661. * Returns an instance of {@link NodeCode} for the given code node.
  32662. *
  32663. * @param {CodeNode} node - The code node.
  32664. * @param {string} type - The node type.
  32665. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32666. * @return {NodeCode} The node code.
  32667. */
  32668. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  32669. const nodeData = this.getDataFromNode( node );
  32670. let nodeCode = nodeData.code;
  32671. if ( nodeCode === undefined ) {
  32672. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  32673. const index = codes.length;
  32674. nodeCode = new NodeCode( 'nodeCode' + index, type );
  32675. codes.push( nodeCode );
  32676. nodeData.code = nodeCode;
  32677. }
  32678. return nodeCode;
  32679. }
  32680. /**
  32681. * Adds a code flow based on the code-block hierarchy.
  32682. * This is used so that code-blocks like If,Else create their variables locally if the Node
  32683. * is only used inside one of these conditionals in the current shader stage.
  32684. *
  32685. * @param {Node} node - The node to add.
  32686. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  32687. */
  32688. addFlowCodeHierarchy( node, nodeBlock ) {
  32689. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  32690. let needsFlowCode = true;
  32691. let nodeBlockHierarchy = nodeBlock;
  32692. while ( nodeBlockHierarchy ) {
  32693. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  32694. needsFlowCode = false;
  32695. break;
  32696. }
  32697. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  32698. }
  32699. if ( needsFlowCode ) {
  32700. for ( const flowCode of flowCodes ) {
  32701. this.addLineFlowCode( flowCode );
  32702. }
  32703. }
  32704. }
  32705. /**
  32706. * Add a inline-code to the current flow code-block.
  32707. *
  32708. * @param {Node} node - The node to add.
  32709. * @param {string} code - The code to add.
  32710. * @param {Node} nodeBlock - Current ConditionalNode
  32711. */
  32712. addLineFlowCodeBlock( node, code, nodeBlock ) {
  32713. const nodeData = this.getDataFromNode( node );
  32714. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  32715. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  32716. flowCodes.push( code );
  32717. codeBlock.set( nodeBlock, true );
  32718. }
  32719. /**
  32720. * Add a inline-code to the current flow.
  32721. *
  32722. * @param {string} code - The code to add.
  32723. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  32724. * @return {NodeBuilder} A reference to this node builder.
  32725. */
  32726. addLineFlowCode( code, node = null ) {
  32727. if ( code === '' ) return this;
  32728. if ( node !== null && this.context.nodeBlock ) {
  32729. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  32730. }
  32731. code = this.tab + code;
  32732. if ( ! /;\s*$/.test( code ) ) {
  32733. code = code + ';\n';
  32734. }
  32735. this.flow.code += code;
  32736. return this;
  32737. }
  32738. /**
  32739. * Adds a code to the current code flow.
  32740. *
  32741. * @param {string} code - Shader code.
  32742. * @return {NodeBuilder} A reference to this node builder.
  32743. */
  32744. addFlowCode( code ) {
  32745. this.flow.code += code;
  32746. return this;
  32747. }
  32748. /**
  32749. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  32750. * Typically used in codes with If,Else.
  32751. *
  32752. * @return {NodeBuilder} A reference to this node builder.
  32753. */
  32754. addFlowTab() {
  32755. this.tab += '\t';
  32756. return this;
  32757. }
  32758. /**
  32759. * Removes a tab.
  32760. *
  32761. * @return {NodeBuilder} A reference to this node builder.
  32762. */
  32763. removeFlowTab() {
  32764. this.tab = this.tab.slice( 0, -1 );
  32765. return this;
  32766. }
  32767. /**
  32768. * Gets the current flow data based on a Node.
  32769. *
  32770. * @param {Node} node - Node that the flow was started.
  32771. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32772. * @return {Object} The flow data.
  32773. */
  32774. getFlowData( node/*, shaderStage*/ ) {
  32775. return this.flowsData.get( node );
  32776. }
  32777. /**
  32778. * Executes the node flow based on a root node to generate the final shader code.
  32779. *
  32780. * @param {Node} node - The node to execute.
  32781. * @return {Object} The code flow.
  32782. */
  32783. flowNode( node ) {
  32784. const output = node.getNodeType( this );
  32785. const flowData = this.flowChildNode( node, output );
  32786. this.flowsData.set( node, flowData );
  32787. return flowData;
  32788. }
  32789. /**
  32790. * Includes a node in the current function node.
  32791. *
  32792. * @param {Node} node - The node to include.
  32793. * @returns {void}
  32794. */
  32795. addInclude( node ) {
  32796. if ( this.currentFunctionNode !== null ) {
  32797. this.currentFunctionNode.includes.push( node );
  32798. }
  32799. }
  32800. /**
  32801. * Returns the native shader operator name for a given generic name.
  32802. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  32803. *
  32804. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  32805. * @return {FunctionNode} The build function node.
  32806. */
  32807. buildFunctionNode( shaderNode ) {
  32808. const fn = new FunctionNode();
  32809. const previous = this.currentFunctionNode;
  32810. this.currentFunctionNode = fn;
  32811. fn.code = this.buildFunctionCode( shaderNode );
  32812. this.currentFunctionNode = previous;
  32813. return fn;
  32814. }
  32815. /**
  32816. * Generates a code flow based on a TSL function: Fn().
  32817. *
  32818. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  32819. * @return {Object}
  32820. */
  32821. flowShaderNode( shaderNode ) {
  32822. const layout = shaderNode.layout;
  32823. const inputs = {
  32824. [ Symbol.iterator ]() {
  32825. let index = 0;
  32826. const values = Object.values( this );
  32827. return {
  32828. next: () => ( {
  32829. value: values[ index ],
  32830. done: index ++ >= values.length
  32831. } )
  32832. };
  32833. }
  32834. };
  32835. for ( const input of layout.inputs ) {
  32836. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  32837. }
  32838. //
  32839. shaderNode.layout = null;
  32840. const callNode = shaderNode.call( inputs );
  32841. const flowData = this.flowStagesNode( callNode, layout.type );
  32842. shaderNode.layout = layout;
  32843. return flowData;
  32844. }
  32845. /**
  32846. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  32847. *
  32848. * @param {Node} node - The node to execute.
  32849. * @param {?string} output - Expected output type. For example 'vec3'.
  32850. * @return {Object}
  32851. */
  32852. flowStagesNode( node, output = null ) {
  32853. const previousFlow = this.flow;
  32854. const previousVars = this.vars;
  32855. const previousDeclarations = this.declarations;
  32856. const previousCache = this.cache;
  32857. const previousBuildStage = this.buildStage;
  32858. const previousStack = this.stack;
  32859. const flow = {
  32860. code: ''
  32861. };
  32862. this.flow = flow;
  32863. this.vars = {};
  32864. this.declarations = {};
  32865. this.cache = new NodeCache();
  32866. this.stack = stack();
  32867. for ( const buildStage of defaultBuildStages ) {
  32868. this.setBuildStage( buildStage );
  32869. flow.result = node.build( this, output );
  32870. }
  32871. flow.vars = this.getVars( this.shaderStage );
  32872. this.flow = previousFlow;
  32873. this.vars = previousVars;
  32874. this.declarations = previousDeclarations;
  32875. this.cache = previousCache;
  32876. this.stack = previousStack;
  32877. this.setBuildStage( previousBuildStage );
  32878. return flow;
  32879. }
  32880. /**
  32881. * Returns the native shader operator name for a given generic name.
  32882. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  32883. *
  32884. * @abstract
  32885. * @param {string} op - The operator name to resolve.
  32886. * @return {?string} The resolved operator name.
  32887. */
  32888. getFunctionOperator( /* op */ ) {
  32889. return null;
  32890. }
  32891. /**
  32892. * Builds the given shader node.
  32893. *
  32894. * @abstract
  32895. * @param {ShaderNodeInternal} shaderNode - The shader node.
  32896. * @return {string} The function code.
  32897. */
  32898. buildFunctionCode( /* shaderNode */ ) {
  32899. console.warn( 'Abstract function.' );
  32900. }
  32901. /**
  32902. * Generates a code flow based on a child Node.
  32903. *
  32904. * @param {Node} node - The node to execute.
  32905. * @param {?string} output - Expected output type. For example 'vec3'.
  32906. * @return {Object} The code flow.
  32907. */
  32908. flowChildNode( node, output = null ) {
  32909. const previousFlow = this.flow;
  32910. const flow = {
  32911. code: ''
  32912. };
  32913. this.flow = flow;
  32914. flow.result = node.build( this, output );
  32915. this.flow = previousFlow;
  32916. return flow;
  32917. }
  32918. /**
  32919. * Executes a flow of code in a different stage.
  32920. *
  32921. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  32922. * return the value in fragment-stage even if it is being executed in an input fragment.
  32923. *
  32924. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32925. * @param {Node} node - The node to execute.
  32926. * @param {?string} output - Expected output type. For example 'vec3'.
  32927. * @param {?string} propertyName - The property name to assign the result.
  32928. * @return {Object}
  32929. */
  32930. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  32931. const previousShaderStage = this.shaderStage;
  32932. this.setShaderStage( shaderStage );
  32933. const flowData = this.flowChildNode( node, output );
  32934. if ( propertyName !== null ) {
  32935. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  32936. }
  32937. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  32938. this.setShaderStage( previousShaderStage );
  32939. return flowData;
  32940. }
  32941. /**
  32942. * Returns an array holding all node attributes of this node builder.
  32943. *
  32944. * @return {Array<NodeAttribute>} The node attributes of this builder.
  32945. */
  32946. getAttributesArray() {
  32947. return this.attributes.concat( this.bufferAttributes );
  32948. }
  32949. /**
  32950. * Returns the attribute definitions as a shader string for the given shader stage.
  32951. *
  32952. * @abstract
  32953. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32954. * @return {string} The attribute code section.
  32955. */
  32956. getAttributes( /*shaderStage*/ ) {
  32957. console.warn( 'Abstract function.' );
  32958. }
  32959. /**
  32960. * Returns the varying definitions as a shader string for the given shader stage.
  32961. *
  32962. * @abstract
  32963. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32964. * @return {string} The varying code section.
  32965. */
  32966. getVaryings( /*shaderStage*/ ) {
  32967. console.warn( 'Abstract function.' );
  32968. }
  32969. /**
  32970. * Returns a single variable definition as a shader string for the given variable type and name.
  32971. *
  32972. * @param {string} type - The variable's type.
  32973. * @param {string} name - The variable's name.
  32974. * @param {?number} [count=null] - The array length.
  32975. * @return {string} The shader string.
  32976. */
  32977. getVar( type, name, count = null ) {
  32978. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  32979. }
  32980. /**
  32981. * Returns the variable definitions as a shader string for the given shader stage.
  32982. *
  32983. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32984. * @return {string} The variable code section.
  32985. */
  32986. getVars( shaderStage ) {
  32987. let snippet = '';
  32988. const vars = this.vars[ shaderStage ];
  32989. if ( vars !== undefined ) {
  32990. for ( const variable of vars ) {
  32991. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  32992. }
  32993. }
  32994. return snippet;
  32995. }
  32996. /**
  32997. * Returns the uniform definitions as a shader string for the given shader stage.
  32998. *
  32999. * @abstract
  33000. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33001. * @return {string} The uniform code section.
  33002. */
  33003. getUniforms( /*shaderStage*/ ) {
  33004. console.warn( 'Abstract function.' );
  33005. }
  33006. /**
  33007. * Returns the native code definitions as a shader string for the given shader stage.
  33008. *
  33009. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33010. * @return {string} The native code section.
  33011. */
  33012. getCodes( shaderStage ) {
  33013. const codes = this.codes[ shaderStage ];
  33014. let code = '';
  33015. if ( codes !== undefined ) {
  33016. for ( const nodeCode of codes ) {
  33017. code += nodeCode.code + '\n';
  33018. }
  33019. }
  33020. return code;
  33021. }
  33022. /**
  33023. * Returns the hash of this node builder.
  33024. *
  33025. * @return {string} The hash.
  33026. */
  33027. getHash() {
  33028. return this.vertexShader + this.fragmentShader + this.computeShader;
  33029. }
  33030. /**
  33031. * Sets the current shader stage.
  33032. *
  33033. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  33034. */
  33035. setShaderStage( shaderStage ) {
  33036. this.shaderStage = shaderStage;
  33037. }
  33038. /**
  33039. * Returns the current shader stage.
  33040. *
  33041. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  33042. */
  33043. getShaderStage() {
  33044. return this.shaderStage;
  33045. }
  33046. /**
  33047. * Sets the current build stage.
  33048. *
  33049. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  33050. */
  33051. setBuildStage( buildStage ) {
  33052. this.buildStage = buildStage;
  33053. }
  33054. /**
  33055. * Returns the current build stage.
  33056. *
  33057. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  33058. */
  33059. getBuildStage() {
  33060. return this.buildStage;
  33061. }
  33062. /**
  33063. * Controls the code build of the shader stages.
  33064. *
  33065. * @abstract
  33066. */
  33067. buildCode() {
  33068. console.warn( 'Abstract function.' );
  33069. }
  33070. /**
  33071. * Central build method which controls the build for the given object.
  33072. *
  33073. * @return {NodeBuilder} A reference to this node builder.
  33074. */
  33075. build() {
  33076. const { object, material, renderer } = this;
  33077. if ( material !== null ) {
  33078. let nodeMaterial = renderer.library.fromMaterial( material );
  33079. if ( nodeMaterial === null ) {
  33080. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  33081. nodeMaterial = new NodeMaterial();
  33082. }
  33083. nodeMaterial.build( this );
  33084. } else {
  33085. this.addFlow( 'compute', object );
  33086. }
  33087. // setup() -> stage 1: create possible new nodes and returns an output reference node
  33088. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  33089. // generate() -> stage 3: generate shader
  33090. for ( const buildStage of defaultBuildStages ) {
  33091. this.setBuildStage( buildStage );
  33092. if ( this.context.vertex && this.context.vertex.isNode ) {
  33093. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  33094. }
  33095. for ( const shaderStage of shaderStages ) {
  33096. this.setShaderStage( shaderStage );
  33097. const flowNodes = this.flowNodes[ shaderStage ];
  33098. for ( const node of flowNodes ) {
  33099. if ( buildStage === 'generate' ) {
  33100. this.flowNode( node );
  33101. } else {
  33102. node.build( this );
  33103. }
  33104. }
  33105. }
  33106. }
  33107. this.setBuildStage( null );
  33108. this.setShaderStage( null );
  33109. // stage 4: build code for a specific output
  33110. this.buildCode();
  33111. this.buildUpdateNodes();
  33112. return this;
  33113. }
  33114. /**
  33115. * Returns a uniform representation which is later used for UBO generation and rendering.
  33116. *
  33117. * @param {NodeUniform} uniformNode - The uniform node.
  33118. * @param {string} type - The requested type.
  33119. * @return {Uniform} The uniform.
  33120. */
  33121. getNodeUniform( uniformNode, type ) {
  33122. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  33123. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  33124. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  33125. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  33126. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  33127. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  33128. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  33129. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  33130. throw new Error( `Uniform "${type}" not declared.` );
  33131. }
  33132. /**
  33133. * Formats the given shader snippet from a given type into another one. E.g.
  33134. * this method might be used to convert a simple float string `"1.0"` into a
  33135. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  33136. *
  33137. * @param {string} snippet - The shader snippet.
  33138. * @param {string} fromType - The source type.
  33139. * @param {string} toType - The target type.
  33140. * @return {string} The updated shader string.
  33141. */
  33142. format( snippet, fromType, toType ) {
  33143. fromType = this.getVectorType( fromType );
  33144. toType = this.getVectorType( toType );
  33145. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  33146. return snippet;
  33147. }
  33148. const fromTypeLength = this.getTypeLength( fromType );
  33149. const toTypeLength = this.getTypeLength( toType );
  33150. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  33151. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  33152. }
  33153. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  33154. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  33155. }
  33156. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  33157. // @TODO: ignore for now
  33158. return snippet;
  33159. }
  33160. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  33161. // @TODO: ignore for now
  33162. return snippet;
  33163. }
  33164. if ( fromTypeLength === toTypeLength ) {
  33165. return `${ this.getType( toType ) }( ${ snippet } )`;
  33166. }
  33167. if ( fromTypeLength > toTypeLength ) {
  33168. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  33169. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  33170. }
  33171. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  33172. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  33173. }
  33174. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  33175. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  33176. }
  33177. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  33178. // convert a number value to vector type, e.g:
  33179. // vec3( 1u ) -> vec3( float( 1u ) )
  33180. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  33181. }
  33182. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  33183. }
  33184. /**
  33185. * Returns a signature with the engine's current revision.
  33186. *
  33187. * @return {string} The signature.
  33188. */
  33189. getSignature() {
  33190. return `// Three.js r${ REVISION } - Node System\n`;
  33191. }
  33192. /**
  33193. * Prevents the node builder from being used as an iterable in TSL.Fn(), avoiding potential runtime errors.
  33194. */
  33195. *[ Symbol.iterator ]() { }
  33196. // Deprecated
  33197. /**
  33198. * @function
  33199. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  33200. *
  33201. * @param {string} [type='NodeMaterial'] - The node material type.
  33202. * @throws {Error}
  33203. */
  33204. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  33205. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  33206. }
  33207. }
  33208. /**
  33209. * Management class for updating nodes. The module tracks metrics like
  33210. * the elapsed time, delta time, the render and frame ID to correctly
  33211. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  33212. * and {@link Node#updateAfter} depending on the node's configuration.
  33213. */
  33214. class NodeFrame {
  33215. /**
  33216. * Constructs a new node fame.
  33217. */
  33218. constructor() {
  33219. /**
  33220. * The elapsed time in seconds.
  33221. *
  33222. * @type {number}
  33223. * @default 0
  33224. */
  33225. this.time = 0;
  33226. /**
  33227. * The delta time in seconds.
  33228. *
  33229. * @type {number}
  33230. * @default 0
  33231. */
  33232. this.deltaTime = 0;
  33233. /**
  33234. * The frame ID.
  33235. *
  33236. * @type {number}
  33237. * @default 0
  33238. */
  33239. this.frameId = 0;
  33240. /**
  33241. * The render ID.
  33242. *
  33243. * @type {number}
  33244. * @default 0
  33245. */
  33246. this.renderId = 0;
  33247. /**
  33248. * Used to control the {@link Node#update} call.
  33249. *
  33250. * @type {WeakMap<Node, Object>}
  33251. */
  33252. this.updateMap = new WeakMap();
  33253. /**
  33254. * Used to control the {@link Node#updateBefore} call.
  33255. *
  33256. * @type {WeakMap<Node, Object>}
  33257. */
  33258. this.updateBeforeMap = new WeakMap();
  33259. /**
  33260. * Used to control the {@link Node#updateAfter} call.
  33261. *
  33262. * @type {WeakMap<Node, Object>}
  33263. */
  33264. this.updateAfterMap = new WeakMap();
  33265. /**
  33266. * A reference to the current renderer.
  33267. *
  33268. * @type {?Renderer}
  33269. * @default null
  33270. */
  33271. this.renderer = null;
  33272. /**
  33273. * A reference to the current material.
  33274. *
  33275. * @type {?Material}
  33276. * @default null
  33277. */
  33278. this.material = null;
  33279. /**
  33280. * A reference to the current camera.
  33281. *
  33282. * @type {?Camera}
  33283. * @default null
  33284. */
  33285. this.camera = null;
  33286. /**
  33287. * A reference to the current 3D object.
  33288. *
  33289. * @type {?Object3D}
  33290. * @default null
  33291. */
  33292. this.object = null;
  33293. /**
  33294. * A reference to the current scene.
  33295. *
  33296. * @type {?Scene}
  33297. * @default null
  33298. */
  33299. this.scene = null;
  33300. }
  33301. /**
  33302. * Returns a dictionary for a given node and update map which
  33303. * is used to correctly call node update methods per frame or render.
  33304. *
  33305. * @private
  33306. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  33307. * @param {Node} nodeRef - The reference to the current node.
  33308. * @return {Object<string,WeakMap>} The dictionary.
  33309. */
  33310. _getMaps( referenceMap, nodeRef ) {
  33311. let maps = referenceMap.get( nodeRef );
  33312. if ( maps === undefined ) {
  33313. maps = {
  33314. renderMap: new WeakMap(),
  33315. frameMap: new WeakMap()
  33316. };
  33317. referenceMap.set( nodeRef, maps );
  33318. }
  33319. return maps;
  33320. }
  33321. /**
  33322. * This method executes the {@link Node#updateBefore} for the given node.
  33323. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  33324. * is only executed once per frame, render or object depending on the update
  33325. * type.
  33326. *
  33327. * @param {Node} node - The node that should be updated.
  33328. */
  33329. updateBeforeNode( node ) {
  33330. const updateType = node.getUpdateBeforeType();
  33331. const reference = node.updateReference( this );
  33332. if ( updateType === NodeUpdateType.FRAME ) {
  33333. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  33334. if ( frameMap.get( reference ) !== this.frameId ) {
  33335. if ( node.updateBefore( this ) !== false ) {
  33336. frameMap.set( reference, this.frameId );
  33337. }
  33338. }
  33339. } else if ( updateType === NodeUpdateType.RENDER ) {
  33340. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  33341. if ( renderMap.get( reference ) !== this.renderId ) {
  33342. if ( node.updateBefore( this ) !== false ) {
  33343. renderMap.set( reference, this.renderId );
  33344. }
  33345. }
  33346. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33347. node.updateBefore( this );
  33348. }
  33349. }
  33350. /**
  33351. * This method executes the {@link Node#updateAfter} for the given node.
  33352. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  33353. * is only executed once per frame, render or object depending on the update
  33354. * type.
  33355. *
  33356. * @param {Node} node - The node that should be updated.
  33357. */
  33358. updateAfterNode( node ) {
  33359. const updateType = node.getUpdateAfterType();
  33360. const reference = node.updateReference( this );
  33361. if ( updateType === NodeUpdateType.FRAME ) {
  33362. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  33363. if ( frameMap.get( reference ) !== this.frameId ) {
  33364. if ( node.updateAfter( this ) !== false ) {
  33365. frameMap.set( reference, this.frameId );
  33366. }
  33367. }
  33368. } else if ( updateType === NodeUpdateType.RENDER ) {
  33369. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  33370. if ( renderMap.get( reference ) !== this.renderId ) {
  33371. if ( node.updateAfter( this ) !== false ) {
  33372. renderMap.set( reference, this.renderId );
  33373. }
  33374. }
  33375. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33376. node.updateAfter( this );
  33377. }
  33378. }
  33379. /**
  33380. * This method executes the {@link Node#update} for the given node.
  33381. * It makes sure {@link Node#updateType} is honored meaning the update
  33382. * is only executed once per frame, render or object depending on the update
  33383. * type.
  33384. *
  33385. * @param {Node} node - The node that should be updated.
  33386. */
  33387. updateNode( node ) {
  33388. const updateType = node.getUpdateType();
  33389. const reference = node.updateReference( this );
  33390. if ( updateType === NodeUpdateType.FRAME ) {
  33391. const { frameMap } = this._getMaps( this.updateMap, reference );
  33392. if ( frameMap.get( reference ) !== this.frameId ) {
  33393. if ( node.update( this ) !== false ) {
  33394. frameMap.set( reference, this.frameId );
  33395. }
  33396. }
  33397. } else if ( updateType === NodeUpdateType.RENDER ) {
  33398. const { renderMap } = this._getMaps( this.updateMap, reference );
  33399. if ( renderMap.get( reference ) !== this.renderId ) {
  33400. if ( node.update( this ) !== false ) {
  33401. renderMap.set( reference, this.renderId );
  33402. }
  33403. }
  33404. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33405. node.update( this );
  33406. }
  33407. }
  33408. /**
  33409. * Updates the internal state of the node frame. This method is
  33410. * called by the renderer in its internal animation loop.
  33411. */
  33412. update() {
  33413. this.frameId ++;
  33414. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  33415. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  33416. this.lastTime = performance.now();
  33417. this.time += this.deltaTime;
  33418. }
  33419. }
  33420. /**
  33421. * Describes the input of a {@link NodeFunction}.
  33422. */
  33423. class NodeFunctionInput {
  33424. /**
  33425. * Constructs a new node function input.
  33426. *
  33427. * @param {string} type - The input type.
  33428. * @param {string} name - The input name.
  33429. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  33430. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  33431. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  33432. */
  33433. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  33434. /**
  33435. * The input type.
  33436. *
  33437. * @type {string}
  33438. */
  33439. this.type = type;
  33440. /**
  33441. * The input name.
  33442. *
  33443. * @type {string}
  33444. */
  33445. this.name = name;
  33446. /**
  33447. * If the input is an Array, count will be the length.
  33448. *
  33449. * @type {?number}
  33450. * @default null
  33451. */
  33452. this.count = count;
  33453. /**
  33454. *The parameter qualifier (only relevant for GLSL).
  33455. *
  33456. * @type {('in'|'out'|'inout')}
  33457. * @default ''
  33458. */
  33459. this.qualifier = qualifier;
  33460. /**
  33461. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  33462. *
  33463. * @type {boolean}
  33464. * @default false
  33465. */
  33466. this.isConst = isConst;
  33467. }
  33468. }
  33469. NodeFunctionInput.isNodeFunctionInput = true;
  33470. /**
  33471. * Module for representing directional lights as nodes.
  33472. *
  33473. * @augments AnalyticLightNode
  33474. */
  33475. class DirectionalLightNode extends AnalyticLightNode {
  33476. static get type() {
  33477. return 'DirectionalLightNode';
  33478. }
  33479. /**
  33480. * Constructs a new directional light node.
  33481. *
  33482. * @param {?DirectionalLight} [light=null] - The directional light source.
  33483. */
  33484. constructor( light = null ) {
  33485. super( light );
  33486. }
  33487. setupDirect() {
  33488. const lightColor = this.colorNode;
  33489. const lightDirection = lightTargetDirection( this.light );
  33490. return { lightDirection, lightColor };
  33491. }
  33492. }
  33493. const _matrix41 = /*@__PURE__*/ new Matrix4();
  33494. const _matrix42 = /*@__PURE__*/ new Matrix4();
  33495. let _ltcLib = null;
  33496. /**
  33497. * Module for representing rect area lights as nodes.
  33498. *
  33499. * @augments AnalyticLightNode
  33500. */
  33501. class RectAreaLightNode extends AnalyticLightNode {
  33502. static get type() {
  33503. return 'RectAreaLightNode';
  33504. }
  33505. /**
  33506. * Constructs a new rect area light node.
  33507. *
  33508. * @param {?RectAreaLight} [light=null] - The rect area light source.
  33509. */
  33510. constructor( light = null ) {
  33511. super( light );
  33512. /**
  33513. * Uniform node representing the half height of the are light.
  33514. *
  33515. * @type {UniformNode<vec3>}
  33516. */
  33517. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  33518. /**
  33519. * Uniform node representing the half width of the are light.
  33520. *
  33521. * @type {UniformNode<vec3>}
  33522. */
  33523. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  33524. /**
  33525. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  33526. * relies on `viewMatrix` which might vary per render call.
  33527. *
  33528. * @type {string}
  33529. * @default 'render'
  33530. */
  33531. this.updateType = NodeUpdateType.RENDER;
  33532. }
  33533. /**
  33534. * Overwritten to updated rect area light specific uniforms.
  33535. *
  33536. * @param {NodeFrame} frame - A reference to the current node frame.
  33537. */
  33538. update( frame ) {
  33539. super.update( frame );
  33540. const { light } = this;
  33541. const viewMatrix = frame.camera.matrixWorldInverse;
  33542. _matrix42.identity();
  33543. _matrix41.copy( light.matrixWorld );
  33544. _matrix41.premultiply( viewMatrix );
  33545. _matrix42.extractRotation( _matrix41 );
  33546. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  33547. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  33548. this.halfWidth.value.applyMatrix4( _matrix42 );
  33549. this.halfHeight.value.applyMatrix4( _matrix42 );
  33550. }
  33551. setupDirectRectArea( builder ) {
  33552. let ltc_1, ltc_2;
  33553. if ( builder.isAvailable( 'float32Filterable' ) ) {
  33554. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  33555. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  33556. } else {
  33557. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  33558. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  33559. }
  33560. const { colorNode, light } = this;
  33561. const lightPosition = lightViewPosition( light );
  33562. return {
  33563. lightColor: colorNode,
  33564. lightPosition,
  33565. halfWidth: this.halfWidth,
  33566. halfHeight: this.halfHeight,
  33567. ltc_1,
  33568. ltc_2
  33569. };
  33570. }
  33571. /**
  33572. * Used to configure the internal BRDF approximation texture data.
  33573. *
  33574. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  33575. */
  33576. static setLTC( ltc ) {
  33577. _ltcLib = ltc;
  33578. }
  33579. }
  33580. /**
  33581. * Module for representing spot lights as nodes.
  33582. *
  33583. * @augments AnalyticLightNode
  33584. */
  33585. class SpotLightNode extends AnalyticLightNode {
  33586. static get type() {
  33587. return 'SpotLightNode';
  33588. }
  33589. /**
  33590. * Constructs a new spot light node.
  33591. *
  33592. * @param {?SpotLight} [light=null] - The spot light source.
  33593. */
  33594. constructor( light = null ) {
  33595. super( light );
  33596. /**
  33597. * Uniform node representing the cone cosine.
  33598. *
  33599. * @type {UniformNode<float>}
  33600. */
  33601. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  33602. /**
  33603. * Uniform node representing the penumbra cosine.
  33604. *
  33605. * @type {UniformNode<float>}
  33606. */
  33607. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  33608. /**
  33609. * Uniform node representing the cutoff distance.
  33610. *
  33611. * @type {UniformNode<float>}
  33612. */
  33613. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  33614. /**
  33615. * Uniform node representing the decay exponent.
  33616. *
  33617. * @type {UniformNode<float>}
  33618. */
  33619. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  33620. }
  33621. /**
  33622. * Overwritten to updated spot light specific uniforms.
  33623. *
  33624. * @param {NodeFrame} frame - A reference to the current node frame.
  33625. */
  33626. update( frame ) {
  33627. super.update( frame );
  33628. const { light } = this;
  33629. this.coneCosNode.value = Math.cos( light.angle );
  33630. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  33631. this.cutoffDistanceNode.value = light.distance;
  33632. this.decayExponentNode.value = light.decay;
  33633. }
  33634. /**
  33635. * Computes the spot attenuation for the given angle.
  33636. *
  33637. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  33638. * @return {Node<float>} The spot attenuation.
  33639. */
  33640. getSpotAttenuation( angleCosine ) {
  33641. const { coneCosNode, penumbraCosNode } = this;
  33642. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  33643. }
  33644. setupDirect( builder ) {
  33645. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  33646. const lightVector = this.getLightVector( builder );
  33647. const lightDirection = lightVector.normalize();
  33648. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  33649. const spotAttenuation = this.getSpotAttenuation( angleCos );
  33650. const lightDistance = lightVector.length();
  33651. const lightAttenuation = getDistanceAttenuation( {
  33652. lightDistance,
  33653. cutoffDistance: cutoffDistanceNode,
  33654. decayExponent: decayExponentNode
  33655. } );
  33656. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  33657. if ( light.map ) {
  33658. const spotLightCoord = lightProjectionUV( light, builder.context.positionWorld );
  33659. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  33660. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  33661. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  33662. }
  33663. return { lightColor, lightDirection };
  33664. }
  33665. }
  33666. /**
  33667. * An IES version of the default spot light node.
  33668. *
  33669. * @augments SpotLightNode
  33670. */
  33671. class IESSpotLightNode extends SpotLightNode {
  33672. static get type() {
  33673. return 'IESSpotLightNode';
  33674. }
  33675. /**
  33676. * Overwrites the default implementation to compute an IES conform spot attenuation.
  33677. *
  33678. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  33679. * @return {Node<float>} The spot attenuation.
  33680. */
  33681. getSpotAttenuation( angleCosine ) {
  33682. const iesMap = this.light.iesMap;
  33683. let spotAttenuation = null;
  33684. if ( iesMap && iesMap.isTexture === true ) {
  33685. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  33686. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  33687. } else {
  33688. spotAttenuation = super.getSpotAttenuation( angleCosine );
  33689. }
  33690. return spotAttenuation;
  33691. }
  33692. }
  33693. /**
  33694. * Module for representing ambient lights as nodes.
  33695. *
  33696. * @augments AnalyticLightNode
  33697. */
  33698. class AmbientLightNode extends AnalyticLightNode {
  33699. static get type() {
  33700. return 'AmbientLightNode';
  33701. }
  33702. /**
  33703. * Constructs a new ambient light node.
  33704. *
  33705. * @param {?AmbientLight} [light=null] - The ambient light source.
  33706. */
  33707. constructor( light = null ) {
  33708. super( light );
  33709. }
  33710. setup( { context } ) {
  33711. context.irradiance.addAssign( this.colorNode );
  33712. }
  33713. }
  33714. /**
  33715. * Module for representing hemisphere lights as nodes.
  33716. *
  33717. * @augments AnalyticLightNode
  33718. */
  33719. class HemisphereLightNode extends AnalyticLightNode {
  33720. static get type() {
  33721. return 'HemisphereLightNode';
  33722. }
  33723. /**
  33724. * Constructs a new hemisphere light node.
  33725. *
  33726. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  33727. */
  33728. constructor( light = null ) {
  33729. super( light );
  33730. /**
  33731. * Uniform node representing the light's position.
  33732. *
  33733. * @type {UniformNode<vec3>}
  33734. */
  33735. this.lightPositionNode = lightPosition( light );
  33736. /**
  33737. * A node representing the light's direction.
  33738. *
  33739. * @type {Node<vec3>}
  33740. */
  33741. this.lightDirectionNode = this.lightPositionNode.normalize();
  33742. /**
  33743. * Uniform node representing the light's ground color.
  33744. *
  33745. * @type {UniformNode<vec3>}
  33746. */
  33747. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  33748. }
  33749. /**
  33750. * Overwritten to updated hemisphere light specific uniforms.
  33751. *
  33752. * @param {NodeFrame} frame - A reference to the current node frame.
  33753. */
  33754. update( frame ) {
  33755. const { light } = this;
  33756. super.update( frame );
  33757. this.lightPositionNode.object3d = light;
  33758. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  33759. }
  33760. setup( builder ) {
  33761. const { colorNode, groundColorNode, lightDirectionNode } = this;
  33762. const dotNL = normalView.dot( lightDirectionNode );
  33763. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  33764. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  33765. builder.context.irradiance.addAssign( irradiance );
  33766. }
  33767. }
  33768. /**
  33769. * Module for representing light probes as nodes.
  33770. *
  33771. * @augments AnalyticLightNode
  33772. */
  33773. class LightProbeNode extends AnalyticLightNode {
  33774. static get type() {
  33775. return 'LightProbeNode';
  33776. }
  33777. /**
  33778. * Constructs a new light probe node.
  33779. *
  33780. * @param {?LightProbe} [light=null] - The light probe.
  33781. */
  33782. constructor( light = null ) {
  33783. super( light );
  33784. const array = [];
  33785. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  33786. /**
  33787. * Light probe represented as a uniform of spherical harmonics.
  33788. *
  33789. * @type {UniformArrayNode}
  33790. */
  33791. this.lightProbe = uniformArray( array );
  33792. }
  33793. /**
  33794. * Overwritten to updated light probe specific uniforms.
  33795. *
  33796. * @param {NodeFrame} frame - A reference to the current node frame.
  33797. */
  33798. update( frame ) {
  33799. const { light } = this;
  33800. super.update( frame );
  33801. //
  33802. for ( let i = 0; i < 9; i ++ ) {
  33803. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  33804. }
  33805. }
  33806. setup( builder ) {
  33807. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  33808. builder.context.irradiance.addAssign( irradiance );
  33809. }
  33810. }
  33811. /**
  33812. * Base class for node parsers. A derived parser must be implemented
  33813. * for each supported native shader language.
  33814. */
  33815. class NodeParser {
  33816. /**
  33817. * The method parses the given native code an returns a node function.
  33818. *
  33819. * @abstract
  33820. * @param {string} source - The native shader code.
  33821. * @return {NodeFunction} A node function.
  33822. */
  33823. parseFunction( /*source*/ ) {
  33824. console.warn( 'Abstract function.' );
  33825. }
  33826. }
  33827. /**
  33828. * Base class for node functions. A derived module must be implemented
  33829. * for each supported native shader language. Similar to other `Node*` modules,
  33830. * this class is only relevant during the building process and not used
  33831. * in user-level code.
  33832. */
  33833. class NodeFunction {
  33834. /**
  33835. * Constructs a new node function.
  33836. *
  33837. * @param {string} type - The node type. This type is the return type of the node function.
  33838. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  33839. * @param {string} [name=''] - The function's name.
  33840. * @param {string} [precision=''] - The precision qualifier.
  33841. */
  33842. constructor( type, inputs, name = '', precision = '' ) {
  33843. /**
  33844. * The node type. This type is the return type of the node function.
  33845. *
  33846. * @type {string}
  33847. */
  33848. this.type = type;
  33849. /**
  33850. * The function's inputs.
  33851. *
  33852. * @type {Array<NodeFunctionInput>}
  33853. */
  33854. this.inputs = inputs;
  33855. /**
  33856. * The name of the uniform.
  33857. *
  33858. * @type {string}
  33859. * @default ''
  33860. */
  33861. this.name = name;
  33862. /**
  33863. * The precision qualifier.
  33864. *
  33865. * @type {string}
  33866. * @default ''
  33867. */
  33868. this.precision = precision;
  33869. }
  33870. /**
  33871. * This method returns the native code of the node function.
  33872. *
  33873. * @abstract
  33874. * @param {string} name - The function's name.
  33875. * @return {string} A shader code.
  33876. */
  33877. getCode( /*name = this.name*/ ) {
  33878. console.warn( 'Abstract function.' );
  33879. }
  33880. }
  33881. NodeFunction.isNodeFunction = true;
  33882. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  33883. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  33884. const pragmaMain = '#pragma main';
  33885. const parse$1 = ( source ) => {
  33886. source = source.trim();
  33887. const pragmaMainIndex = source.indexOf( pragmaMain );
  33888. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  33889. const declaration = mainCode.match( declarationRegexp$1 );
  33890. if ( declaration !== null && declaration.length === 5 ) {
  33891. // tokenizer
  33892. const inputsCode = declaration[ 4 ];
  33893. const propsMatches = [];
  33894. let nameMatch = null;
  33895. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  33896. propsMatches.push( nameMatch );
  33897. }
  33898. // parser
  33899. const inputs = [];
  33900. let i = 0;
  33901. while ( i < propsMatches.length ) {
  33902. const isConst = propsMatches[ i ][ 0 ] === 'const';
  33903. if ( isConst === true ) {
  33904. i ++;
  33905. }
  33906. let qualifier = propsMatches[ i ][ 0 ];
  33907. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  33908. i ++;
  33909. } else {
  33910. qualifier = '';
  33911. }
  33912. const type = propsMatches[ i ++ ][ 0 ];
  33913. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  33914. if ( Number.isNaN( count ) === false ) i ++;
  33915. else count = null;
  33916. const name = propsMatches[ i ++ ][ 0 ];
  33917. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  33918. }
  33919. //
  33920. const blockCode = mainCode.substring( declaration[ 0 ].length );
  33921. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  33922. const type = declaration[ 2 ];
  33923. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  33924. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  33925. return {
  33926. type,
  33927. inputs,
  33928. name,
  33929. precision,
  33930. inputsCode,
  33931. blockCode,
  33932. headerCode
  33933. };
  33934. } else {
  33935. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  33936. }
  33937. };
  33938. /**
  33939. * This class represents a GLSL node function.
  33940. *
  33941. * @augments NodeFunction
  33942. */
  33943. class GLSLNodeFunction extends NodeFunction {
  33944. /**
  33945. * Constructs a new GLSL node function.
  33946. *
  33947. * @param {string} source - The GLSL source.
  33948. */
  33949. constructor( source ) {
  33950. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  33951. super( type, inputs, name, precision );
  33952. this.inputsCode = inputsCode;
  33953. this.blockCode = blockCode;
  33954. this.headerCode = headerCode;
  33955. }
  33956. /**
  33957. * This method returns the GLSL code of the node function.
  33958. *
  33959. * @param {string} [name=this.name] - The function's name.
  33960. * @return {string} The shader code.
  33961. */
  33962. getCode( name = this.name ) {
  33963. let code;
  33964. const blockCode = this.blockCode;
  33965. if ( blockCode !== '' ) {
  33966. const { type, inputsCode, headerCode, precision } = this;
  33967. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  33968. if ( precision !== '' ) {
  33969. declarationCode = `${ precision } ${ declarationCode }`;
  33970. }
  33971. code = headerCode + declarationCode + blockCode;
  33972. } else {
  33973. // interface function
  33974. code = '';
  33975. }
  33976. return code;
  33977. }
  33978. }
  33979. /**
  33980. * A GLSL node parser.
  33981. *
  33982. * @augments NodeParser
  33983. */
  33984. class GLSLNodeParser extends NodeParser {
  33985. /**
  33986. * The method parses the given GLSL code an returns a node function.
  33987. *
  33988. * @param {string} source - The GLSL code.
  33989. * @return {GLSLNodeFunction} A node function.
  33990. */
  33991. parseFunction( source ) {
  33992. return new GLSLNodeFunction( source );
  33993. }
  33994. }
  33995. const _outputNodeMap = new WeakMap();
  33996. const _chainKeys$2 = [];
  33997. const _cacheKeyValues = [];
  33998. /**
  33999. * This renderer module manages node-related objects and is the
  34000. * primary interface between the renderer and the node system.
  34001. *
  34002. * @private
  34003. * @augments DataMap
  34004. */
  34005. class Nodes extends DataMap {
  34006. /**
  34007. * Constructs a new nodes management component.
  34008. *
  34009. * @param {Renderer} renderer - The renderer.
  34010. * @param {Backend} backend - The renderer's backend.
  34011. */
  34012. constructor( renderer, backend ) {
  34013. super();
  34014. /**
  34015. * The renderer.
  34016. *
  34017. * @type {Renderer}
  34018. */
  34019. this.renderer = renderer;
  34020. /**
  34021. * The renderer's backend.
  34022. *
  34023. * @type {Backend}
  34024. */
  34025. this.backend = backend;
  34026. /**
  34027. * The node frame.
  34028. *
  34029. * @type {Renderer}
  34030. */
  34031. this.nodeFrame = new NodeFrame();
  34032. /**
  34033. * A cache for managing node builder states.
  34034. *
  34035. * @type {Map<number,NodeBuilderState>}
  34036. */
  34037. this.nodeBuilderCache = new Map();
  34038. /**
  34039. * A cache for managing data cache key data.
  34040. *
  34041. * @type {ChainMap}
  34042. */
  34043. this.callHashCache = new ChainMap();
  34044. /**
  34045. * A cache for managing node uniforms group data.
  34046. *
  34047. * @type {ChainMap}
  34048. */
  34049. this.groupsData = new ChainMap();
  34050. /**
  34051. * A cache for managing node objects of
  34052. * scene properties like fog or environments.
  34053. *
  34054. * @type {Object<string,WeakMap>}
  34055. */
  34056. this.cacheLib = {};
  34057. }
  34058. /**
  34059. * Returns `true` if the given node uniforms group must be updated or not.
  34060. *
  34061. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  34062. * @return {boolean} Whether the node uniforms group requires an update or not.
  34063. */
  34064. updateGroup( nodeUniformsGroup ) {
  34065. const groupNode = nodeUniformsGroup.groupNode;
  34066. const name = groupNode.name;
  34067. // objectGroup is always updated
  34068. if ( name === objectGroup.name ) return true;
  34069. // renderGroup is updated once per render/compute call
  34070. if ( name === renderGroup.name ) {
  34071. const uniformsGroupData = this.get( nodeUniformsGroup );
  34072. const renderId = this.nodeFrame.renderId;
  34073. if ( uniformsGroupData.renderId !== renderId ) {
  34074. uniformsGroupData.renderId = renderId;
  34075. return true;
  34076. }
  34077. return false;
  34078. }
  34079. // frameGroup is updated once per frame
  34080. if ( name === frameGroup.name ) {
  34081. const uniformsGroupData = this.get( nodeUniformsGroup );
  34082. const frameId = this.nodeFrame.frameId;
  34083. if ( uniformsGroupData.frameId !== frameId ) {
  34084. uniformsGroupData.frameId = frameId;
  34085. return true;
  34086. }
  34087. return false;
  34088. }
  34089. // other groups are updated just when groupNode.needsUpdate is true
  34090. _chainKeys$2[ 0 ] = groupNode;
  34091. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  34092. let groupData = this.groupsData.get( _chainKeys$2 );
  34093. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  34094. _chainKeys$2.length = 0;
  34095. if ( groupData.version !== groupNode.version ) {
  34096. groupData.version = groupNode.version;
  34097. return true;
  34098. }
  34099. return false;
  34100. }
  34101. /**
  34102. * Returns the cache key for the given render object.
  34103. *
  34104. * @param {RenderObject} renderObject - The render object.
  34105. * @return {number} The cache key.
  34106. */
  34107. getForRenderCacheKey( renderObject ) {
  34108. return renderObject.initialCacheKey;
  34109. }
  34110. /**
  34111. * Returns a node builder state for the given render object.
  34112. *
  34113. * @param {RenderObject} renderObject - The render object.
  34114. * @return {NodeBuilderState} The node builder state.
  34115. */
  34116. getForRender( renderObject ) {
  34117. const renderObjectData = this.get( renderObject );
  34118. let nodeBuilderState = renderObjectData.nodeBuilderState;
  34119. if ( nodeBuilderState === undefined ) {
  34120. const { nodeBuilderCache } = this;
  34121. const cacheKey = this.getForRenderCacheKey( renderObject );
  34122. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  34123. if ( nodeBuilderState === undefined ) {
  34124. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  34125. nodeBuilder.scene = renderObject.scene;
  34126. nodeBuilder.material = renderObject.material;
  34127. nodeBuilder.camera = renderObject.camera;
  34128. nodeBuilder.context.material = renderObject.material;
  34129. nodeBuilder.lightsNode = renderObject.lightsNode;
  34130. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  34131. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  34132. nodeBuilder.clippingContext = renderObject.clippingContext;
  34133. if ( this.renderer.getRenderTarget() ? this.renderer.getRenderTarget().multiview : false ) {
  34134. nodeBuilder.enableMultiview();
  34135. }
  34136. nodeBuilder.build();
  34137. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34138. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  34139. }
  34140. nodeBuilderState.usedTimes ++;
  34141. renderObjectData.nodeBuilderState = nodeBuilderState;
  34142. }
  34143. return nodeBuilderState;
  34144. }
  34145. /**
  34146. * Deletes the given object from the internal data map
  34147. *
  34148. * @param {any} object - The object to delete.
  34149. * @return {?Object} The deleted dictionary.
  34150. */
  34151. delete( object ) {
  34152. if ( object.isRenderObject ) {
  34153. const nodeBuilderState = this.get( object ).nodeBuilderState;
  34154. nodeBuilderState.usedTimes --;
  34155. if ( nodeBuilderState.usedTimes === 0 ) {
  34156. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  34157. }
  34158. }
  34159. return super.delete( object );
  34160. }
  34161. /**
  34162. * Returns a node builder state for the given compute node.
  34163. *
  34164. * @param {Node} computeNode - The compute node.
  34165. * @return {NodeBuilderState} The node builder state.
  34166. */
  34167. getForCompute( computeNode ) {
  34168. const computeData = this.get( computeNode );
  34169. let nodeBuilderState = computeData.nodeBuilderState;
  34170. if ( nodeBuilderState === undefined ) {
  34171. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  34172. nodeBuilder.build();
  34173. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34174. computeData.nodeBuilderState = nodeBuilderState;
  34175. }
  34176. return nodeBuilderState;
  34177. }
  34178. /**
  34179. * Creates a node builder state for the given node builder.
  34180. *
  34181. * @private
  34182. * @param {NodeBuilder} nodeBuilder - The node builder.
  34183. * @return {NodeBuilderState} The node builder state.
  34184. */
  34185. _createNodeBuilderState( nodeBuilder ) {
  34186. return new NodeBuilderState(
  34187. nodeBuilder.vertexShader,
  34188. nodeBuilder.fragmentShader,
  34189. nodeBuilder.computeShader,
  34190. nodeBuilder.getAttributesArray(),
  34191. nodeBuilder.getBindings(),
  34192. nodeBuilder.updateNodes,
  34193. nodeBuilder.updateBeforeNodes,
  34194. nodeBuilder.updateAfterNodes,
  34195. nodeBuilder.observer,
  34196. nodeBuilder.transforms
  34197. );
  34198. }
  34199. /**
  34200. * Returns an environment node for the current configured
  34201. * scene environment.
  34202. *
  34203. * @param {Scene} scene - The scene.
  34204. * @return {Node} A node representing the current scene environment.
  34205. */
  34206. getEnvironmentNode( scene ) {
  34207. this.updateEnvironment( scene );
  34208. let environmentNode = null;
  34209. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  34210. environmentNode = scene.environmentNode;
  34211. } else {
  34212. const sceneData = this.get( scene );
  34213. if ( sceneData.environmentNode ) {
  34214. environmentNode = sceneData.environmentNode;
  34215. }
  34216. }
  34217. return environmentNode;
  34218. }
  34219. /**
  34220. * Returns a background node for the current configured
  34221. * scene background.
  34222. *
  34223. * @param {Scene} scene - The scene.
  34224. * @return {Node} A node representing the current scene background.
  34225. */
  34226. getBackgroundNode( scene ) {
  34227. this.updateBackground( scene );
  34228. let backgroundNode = null;
  34229. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  34230. backgroundNode = scene.backgroundNode;
  34231. } else {
  34232. const sceneData = this.get( scene );
  34233. if ( sceneData.backgroundNode ) {
  34234. backgroundNode = sceneData.backgroundNode;
  34235. }
  34236. }
  34237. return backgroundNode;
  34238. }
  34239. /**
  34240. * Returns a fog node for the current configured scene fog.
  34241. *
  34242. * @param {Scene} scene - The scene.
  34243. * @return {Node} A node representing the current scene fog.
  34244. */
  34245. getFogNode( scene ) {
  34246. this.updateFog( scene );
  34247. return scene.fogNode || this.get( scene ).fogNode || null;
  34248. }
  34249. /**
  34250. * Returns a cache key for the given scene and lights node.
  34251. * This key is used by `RenderObject` as a part of the dynamic
  34252. * cache key (a key that must be checked every time the render
  34253. * objects is drawn).
  34254. *
  34255. * @param {Scene} scene - The scene.
  34256. * @param {LightsNode} lightsNode - The lights node.
  34257. * @return {number} The cache key.
  34258. */
  34259. getCacheKey( scene, lightsNode ) {
  34260. _chainKeys$2[ 0 ] = scene;
  34261. _chainKeys$2[ 1 ] = lightsNode;
  34262. const callId = this.renderer.info.calls;
  34263. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  34264. if ( cacheKeyData.callId !== callId ) {
  34265. const environmentNode = this.getEnvironmentNode( scene );
  34266. const fogNode = this.getFogNode( scene );
  34267. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  34268. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  34269. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  34270. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  34271. cacheKeyData.callId = callId;
  34272. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  34273. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  34274. _cacheKeyValues.length = 0;
  34275. }
  34276. _chainKeys$2.length = 0;
  34277. return cacheKeyData.cacheKey;
  34278. }
  34279. /**
  34280. * A boolean that indicates whether tone mapping should be enabled
  34281. * or not.
  34282. *
  34283. * @type {boolean}
  34284. */
  34285. get isToneMappingState() {
  34286. return this.renderer.getRenderTarget() ? false : true;
  34287. }
  34288. /**
  34289. * If a scene background is configured, this method makes sure to
  34290. * represent the background with a corresponding node-based implementation.
  34291. *
  34292. * @param {Scene} scene - The scene.
  34293. */
  34294. updateBackground( scene ) {
  34295. const sceneData = this.get( scene );
  34296. const background = scene.background;
  34297. if ( background ) {
  34298. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  34299. if ( sceneData.background !== background || forceUpdate ) {
  34300. const backgroundNode = this.getCacheNode( 'background', background, () => {
  34301. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  34302. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  34303. return pmremTexture( background );
  34304. } else {
  34305. let envMap;
  34306. if ( background.isCubeTexture === true ) {
  34307. envMap = cubeTexture( background );
  34308. } else {
  34309. envMap = texture( background );
  34310. }
  34311. return cubeMapNode( envMap );
  34312. }
  34313. } else if ( background.isTexture === true ) {
  34314. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  34315. } else if ( background.isColor !== true ) {
  34316. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  34317. }
  34318. }, forceUpdate );
  34319. sceneData.backgroundNode = backgroundNode;
  34320. sceneData.background = background;
  34321. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  34322. }
  34323. } else if ( sceneData.backgroundNode ) {
  34324. delete sceneData.backgroundNode;
  34325. delete sceneData.background;
  34326. }
  34327. }
  34328. /**
  34329. * This method is part of the caching of nodes which are used to represents the
  34330. * scene's background, fog or environment.
  34331. *
  34332. * @param {string} type - The type of object to cache.
  34333. * @param {Object} object - The object.
  34334. * @param {Function} callback - A callback that produces a node representation for the given object.
  34335. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  34336. * @return {Node} The node representation.
  34337. */
  34338. getCacheNode( type, object, callback, forceUpdate = false ) {
  34339. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  34340. let node = nodeCache.get( object );
  34341. if ( node === undefined || forceUpdate ) {
  34342. node = callback();
  34343. nodeCache.set( object, node );
  34344. }
  34345. return node;
  34346. }
  34347. /**
  34348. * If a scene fog is configured, this method makes sure to
  34349. * represent the fog with a corresponding node-based implementation.
  34350. *
  34351. * @param {Scene} scene - The scene.
  34352. */
  34353. updateFog( scene ) {
  34354. const sceneData = this.get( scene );
  34355. const sceneFog = scene.fog;
  34356. if ( sceneFog ) {
  34357. if ( sceneData.fog !== sceneFog ) {
  34358. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  34359. if ( sceneFog.isFogExp2 ) {
  34360. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34361. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  34362. return fog( color, densityFogFactor( density ) );
  34363. } else if ( sceneFog.isFog ) {
  34364. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34365. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  34366. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  34367. return fog( color, rangeFogFactor( near, far ) );
  34368. } else {
  34369. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  34370. }
  34371. } );
  34372. sceneData.fogNode = fogNode;
  34373. sceneData.fog = sceneFog;
  34374. }
  34375. } else {
  34376. delete sceneData.fogNode;
  34377. delete sceneData.fog;
  34378. }
  34379. }
  34380. /**
  34381. * If a scene environment is configured, this method makes sure to
  34382. * represent the environment with a corresponding node-based implementation.
  34383. *
  34384. * @param {Scene} scene - The scene.
  34385. */
  34386. updateEnvironment( scene ) {
  34387. const sceneData = this.get( scene );
  34388. const environment = scene.environment;
  34389. if ( environment ) {
  34390. if ( sceneData.environment !== environment ) {
  34391. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  34392. if ( environment.isCubeTexture === true ) {
  34393. return cubeTexture( environment );
  34394. } else if ( environment.isTexture === true ) {
  34395. return texture( environment );
  34396. } else {
  34397. console.error( 'Nodes: Unsupported environment configuration.', environment );
  34398. }
  34399. } );
  34400. sceneData.environmentNode = environmentNode;
  34401. sceneData.environment = environment;
  34402. }
  34403. } else if ( sceneData.environmentNode ) {
  34404. delete sceneData.environmentNode;
  34405. delete sceneData.environment;
  34406. }
  34407. }
  34408. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  34409. const nodeFrame = this.nodeFrame;
  34410. nodeFrame.renderer = renderer;
  34411. nodeFrame.scene = scene;
  34412. nodeFrame.object = object;
  34413. nodeFrame.camera = camera;
  34414. nodeFrame.material = material;
  34415. return nodeFrame;
  34416. }
  34417. getNodeFrameForRender( renderObject ) {
  34418. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  34419. }
  34420. /**
  34421. * Returns the current output cache key.
  34422. *
  34423. * @return {string} The output cache key.
  34424. */
  34425. getOutputCacheKey() {
  34426. const renderer = this.renderer;
  34427. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  34428. }
  34429. /**
  34430. * Checks if the output configuration (tone mapping and color space) for
  34431. * the given target has changed.
  34432. *
  34433. * @param {Texture} outputTarget - The output target.
  34434. * @return {boolean} Whether the output configuration has changed or not.
  34435. */
  34436. hasOutputChange( outputTarget ) {
  34437. const cacheKey = _outputNodeMap.get( outputTarget );
  34438. return cacheKey !== this.getOutputCacheKey();
  34439. }
  34440. /**
  34441. * Returns a node that represents the output configuration (tone mapping and
  34442. * color space) for the current target.
  34443. *
  34444. * @param {Texture} outputTarget - The output target.
  34445. * @return {Node} The output node.
  34446. */
  34447. getOutputNode( outputTarget ) {
  34448. const renderer = this.renderer;
  34449. const cacheKey = this.getOutputCacheKey();
  34450. const output = outputTarget.isTextureArray ?
  34451. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  34452. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  34453. _outputNodeMap.set( outputTarget, cacheKey );
  34454. return output;
  34455. }
  34456. /**
  34457. * Triggers the call of `updateBefore()` methods
  34458. * for all nodes of the given render object.
  34459. *
  34460. * @param {RenderObject} renderObject - The render object.
  34461. */
  34462. updateBefore( renderObject ) {
  34463. const nodeBuilder = renderObject.getNodeBuilderState();
  34464. for ( const node of nodeBuilder.updateBeforeNodes ) {
  34465. // update frame state for each node
  34466. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  34467. }
  34468. }
  34469. /**
  34470. * Triggers the call of `updateAfter()` methods
  34471. * for all nodes of the given render object.
  34472. *
  34473. * @param {RenderObject} renderObject - The render object.
  34474. */
  34475. updateAfter( renderObject ) {
  34476. const nodeBuilder = renderObject.getNodeBuilderState();
  34477. for ( const node of nodeBuilder.updateAfterNodes ) {
  34478. // update frame state for each node
  34479. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  34480. }
  34481. }
  34482. /**
  34483. * Triggers the call of `update()` methods
  34484. * for all nodes of the given compute node.
  34485. *
  34486. * @param {Node} computeNode - The compute node.
  34487. */
  34488. updateForCompute( computeNode ) {
  34489. const nodeFrame = this.getNodeFrame();
  34490. const nodeBuilder = this.getForCompute( computeNode );
  34491. for ( const node of nodeBuilder.updateNodes ) {
  34492. nodeFrame.updateNode( node );
  34493. }
  34494. }
  34495. /**
  34496. * Triggers the call of `update()` methods
  34497. * for all nodes of the given compute node.
  34498. *
  34499. * @param {RenderObject} renderObject - The render object.
  34500. */
  34501. updateForRender( renderObject ) {
  34502. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34503. const nodeBuilder = renderObject.getNodeBuilderState();
  34504. for ( const node of nodeBuilder.updateNodes ) {
  34505. nodeFrame.updateNode( node );
  34506. }
  34507. }
  34508. /**
  34509. * Returns `true` if the given render object requires a refresh.
  34510. *
  34511. * @param {RenderObject} renderObject - The render object.
  34512. * @return {boolean} Whether the given render object requires a refresh or not.
  34513. */
  34514. needsRefresh( renderObject ) {
  34515. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34516. const monitor = renderObject.getMonitor();
  34517. return monitor.needsRefresh( renderObject, nodeFrame );
  34518. }
  34519. /**
  34520. * Frees the internal resources.
  34521. */
  34522. dispose() {
  34523. super.dispose();
  34524. this.nodeFrame = new NodeFrame();
  34525. this.nodeBuilderCache = new Map();
  34526. this.cacheLib = {};
  34527. }
  34528. }
  34529. const _plane = /*@__PURE__*/ new Plane();
  34530. /**
  34531. * Represents the state that is used to perform clipping via clipping planes.
  34532. * There is a default clipping context for each render context. When the
  34533. * scene holds instances of `ClippingGroup`, there will be a context for each
  34534. * group.
  34535. *
  34536. * @private
  34537. */
  34538. class ClippingContext {
  34539. /**
  34540. * Constructs a new clipping context.
  34541. *
  34542. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  34543. */
  34544. constructor( parentContext = null ) {
  34545. /**
  34546. * The clipping context's version.
  34547. *
  34548. * @type {number}
  34549. * @readonly
  34550. */
  34551. this.version = 0;
  34552. /**
  34553. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  34554. *
  34555. * @type {?boolean}
  34556. * @default null
  34557. */
  34558. this.clipIntersection = null;
  34559. /**
  34560. * The clipping context's cache key.
  34561. *
  34562. * @type {string}
  34563. */
  34564. this.cacheKey = '';
  34565. /**
  34566. * Whether the shadow pass is active or not.
  34567. *
  34568. * @type {boolean}
  34569. * @default false
  34570. */
  34571. this.shadowPass = false;
  34572. /**
  34573. * The view normal matrix.
  34574. *
  34575. * @type {Matrix3}
  34576. */
  34577. this.viewNormalMatrix = new Matrix3();
  34578. /**
  34579. * Internal cache for maintaining clipping contexts.
  34580. *
  34581. * @type {WeakMap<ClippingGroup,ClippingContext>}
  34582. */
  34583. this.clippingGroupContexts = new WeakMap();
  34584. /**
  34585. * The intersection planes.
  34586. *
  34587. * @type {Array<Vector4>}
  34588. */
  34589. this.intersectionPlanes = [];
  34590. /**
  34591. * The intersection planes.
  34592. *
  34593. * @type {Array<Vector4>}
  34594. */
  34595. this.unionPlanes = [];
  34596. /**
  34597. * The version of the clipping context's parent context.
  34598. *
  34599. * @type {?number}
  34600. * @readonly
  34601. */
  34602. this.parentVersion = null;
  34603. if ( parentContext !== null ) {
  34604. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  34605. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  34606. this.shadowPass = parentContext.shadowPass;
  34607. this.viewMatrix = parentContext.viewMatrix;
  34608. }
  34609. }
  34610. /**
  34611. * Projects the given source clipping planes and writes the result into the
  34612. * destination array.
  34613. *
  34614. * @param {Array<Plane>} source - The source clipping planes.
  34615. * @param {Array<Vector4>} destination - The destination.
  34616. * @param {number} offset - The offset.
  34617. */
  34618. projectPlanes( source, destination, offset ) {
  34619. const l = source.length;
  34620. for ( let i = 0; i < l; i ++ ) {
  34621. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  34622. const v = destination[ offset + i ];
  34623. const normal = _plane.normal;
  34624. v.x = - normal.x;
  34625. v.y = - normal.y;
  34626. v.z = - normal.z;
  34627. v.w = _plane.constant;
  34628. }
  34629. }
  34630. /**
  34631. * Updates the root clipping context of a scene.
  34632. *
  34633. * @param {Scene} scene - The scene.
  34634. * @param {Camera} camera - The camera that is used to render the scene.
  34635. */
  34636. updateGlobal( scene, camera ) {
  34637. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  34638. this.viewMatrix = camera.matrixWorldInverse;
  34639. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  34640. }
  34641. /**
  34642. * Updates the clipping context.
  34643. *
  34644. * @param {ClippingContext} parentContext - The parent context.
  34645. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  34646. */
  34647. update( parentContext, clippingGroup ) {
  34648. let update = false;
  34649. if ( parentContext.version !== this.parentVersion ) {
  34650. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  34651. this.unionPlanes = Array.from( parentContext.unionPlanes );
  34652. this.parentVersion = parentContext.version;
  34653. }
  34654. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  34655. this.clipIntersection = clippingGroup.clipIntersection;
  34656. if ( this.clipIntersection ) {
  34657. this.unionPlanes.length = parentContext.unionPlanes.length;
  34658. } else {
  34659. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  34660. }
  34661. }
  34662. const srcClippingPlanes = clippingGroup.clippingPlanes;
  34663. const l = srcClippingPlanes.length;
  34664. let dstClippingPlanes;
  34665. let offset;
  34666. if ( this.clipIntersection ) {
  34667. dstClippingPlanes = this.intersectionPlanes;
  34668. offset = parentContext.intersectionPlanes.length;
  34669. } else {
  34670. dstClippingPlanes = this.unionPlanes;
  34671. offset = parentContext.unionPlanes.length;
  34672. }
  34673. if ( dstClippingPlanes.length !== offset + l ) {
  34674. dstClippingPlanes.length = offset + l;
  34675. for ( let i = 0; i < l; i ++ ) {
  34676. dstClippingPlanes[ offset + i ] = new Vector4();
  34677. }
  34678. update = true;
  34679. }
  34680. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  34681. if ( update ) {
  34682. this.version ++;
  34683. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  34684. }
  34685. }
  34686. /**
  34687. * Returns a clipping context for the given clipping group.
  34688. *
  34689. * @param {ClippingGroup} clippingGroup - The clipping group.
  34690. * @return {ClippingContext} The clipping context.
  34691. */
  34692. getGroupContext( clippingGroup ) {
  34693. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  34694. let context = this.clippingGroupContexts.get( clippingGroup );
  34695. if ( context === undefined ) {
  34696. context = new ClippingContext( this );
  34697. this.clippingGroupContexts.set( clippingGroup, context );
  34698. }
  34699. context.update( this, clippingGroup );
  34700. return context;
  34701. }
  34702. /**
  34703. * The count of union clipping planes.
  34704. *
  34705. * @type {number}
  34706. * @readonly
  34707. */
  34708. get unionClippingCount() {
  34709. return this.unionPlanes.length;
  34710. }
  34711. }
  34712. /**
  34713. * This module is used to represent render bundles inside the renderer
  34714. * for further processing.
  34715. *
  34716. * @private
  34717. */
  34718. class RenderBundle {
  34719. /**
  34720. * Constructs a new bundle group.
  34721. *
  34722. * @param {BundleGroup} bundleGroup - The bundle group.
  34723. * @param {Camera} camera - The camera the bundle group is rendered with.
  34724. */
  34725. constructor( bundleGroup, camera ) {
  34726. this.bundleGroup = bundleGroup;
  34727. this.camera = camera;
  34728. }
  34729. }
  34730. const _chainKeys$1 = [];
  34731. /**
  34732. * This renderer module manages render bundles.
  34733. *
  34734. * @private
  34735. */
  34736. class RenderBundles {
  34737. /**
  34738. * Constructs a new render bundle management component.
  34739. */
  34740. constructor() {
  34741. /**
  34742. * A chain map for maintaining the render bundles.
  34743. *
  34744. * @type {ChainMap}
  34745. */
  34746. this.bundles = new ChainMap();
  34747. }
  34748. /**
  34749. * Returns a render bundle for the given bundle group and camera.
  34750. *
  34751. * @param {BundleGroup} bundleGroup - The bundle group.
  34752. * @param {Camera} camera - The camera the bundle group is rendered with.
  34753. * @return {RenderBundle} The render bundle.
  34754. */
  34755. get( bundleGroup, camera ) {
  34756. const bundles = this.bundles;
  34757. _chainKeys$1[ 0 ] = bundleGroup;
  34758. _chainKeys$1[ 1 ] = camera;
  34759. let bundle = bundles.get( _chainKeys$1 );
  34760. if ( bundle === undefined ) {
  34761. bundle = new RenderBundle( bundleGroup, camera );
  34762. bundles.set( _chainKeys$1, bundle );
  34763. }
  34764. _chainKeys$1.length = 0;
  34765. return bundle;
  34766. }
  34767. /**
  34768. * Frees all internal resources.
  34769. */
  34770. dispose() {
  34771. this.bundles = new ChainMap();
  34772. }
  34773. }
  34774. /**
  34775. * The purpose of a node library is to assign node implementations
  34776. * to existing library features. In `WebGPURenderer` lights, materials
  34777. * which are not based on `NodeMaterial` as well as tone mapping techniques
  34778. * are implemented with node-based modules.
  34779. *
  34780. * @private
  34781. */
  34782. class NodeLibrary {
  34783. /**
  34784. * Constructs a new node library.
  34785. */
  34786. constructor() {
  34787. /**
  34788. * A weak map that maps lights to light nodes.
  34789. *
  34790. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  34791. */
  34792. this.lightNodes = new WeakMap();
  34793. /**
  34794. * A map that maps materials to node materials.
  34795. *
  34796. * @type {Map<string,NodeMaterial.constructor>}
  34797. */
  34798. this.materialNodes = new Map();
  34799. /**
  34800. * A map that maps tone mapping techniques (constants)
  34801. * to tone mapping node functions.
  34802. *
  34803. * @type {Map<number,Function>}
  34804. */
  34805. this.toneMappingNodes = new Map();
  34806. }
  34807. /**
  34808. * Returns a matching node material instance for the given material object.
  34809. *
  34810. * This method also assigns/copies the properties of the given material object
  34811. * to the node material. This is done to make sure the current material
  34812. * configuration carries over to the node version.
  34813. *
  34814. * @param {Material} material - A material.
  34815. * @return {NodeMaterial} The corresponding node material.
  34816. */
  34817. fromMaterial( material ) {
  34818. if ( material.isNodeMaterial ) return material;
  34819. let nodeMaterial = null;
  34820. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  34821. if ( nodeMaterialClass !== null ) {
  34822. nodeMaterial = new nodeMaterialClass();
  34823. for ( const key in material ) {
  34824. nodeMaterial[ key ] = material[ key ];
  34825. }
  34826. }
  34827. return nodeMaterial;
  34828. }
  34829. /**
  34830. * Adds a tone mapping node function for a tone mapping technique (constant).
  34831. *
  34832. * @param {Function} toneMappingNode - The tone mapping node function.
  34833. * @param {number} toneMapping - The tone mapping.
  34834. */
  34835. addToneMapping( toneMappingNode, toneMapping ) {
  34836. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  34837. }
  34838. /**
  34839. * Returns a tone mapping node function for a tone mapping technique (constant).
  34840. *
  34841. * @param {number} toneMapping - The tone mapping.
  34842. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  34843. */
  34844. getToneMappingFunction( toneMapping ) {
  34845. return this.toneMappingNodes.get( toneMapping ) || null;
  34846. }
  34847. /**
  34848. * Returns a node material class definition for a material type.
  34849. *
  34850. * @param {string} materialType - The material type.
  34851. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  34852. */
  34853. getMaterialNodeClass( materialType ) {
  34854. return this.materialNodes.get( materialType ) || null;
  34855. }
  34856. /**
  34857. * Adds a node material class definition for a given material type.
  34858. *
  34859. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  34860. * @param {string} materialClassType - The material type.
  34861. */
  34862. addMaterial( materialNodeClass, materialClassType ) {
  34863. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  34864. }
  34865. /**
  34866. * Returns a light node class definition for a light class definition.
  34867. *
  34868. * @param {Light.constructor} light - The light class definition.
  34869. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  34870. */
  34871. getLightNodeClass( light ) {
  34872. return this.lightNodes.get( light ) || null;
  34873. }
  34874. /**
  34875. * Adds a light node class definition for a given light class definition.
  34876. *
  34877. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  34878. * @param {Light.constructor} lightClass - The light class definition.
  34879. */
  34880. addLight( lightNodeClass, lightClass ) {
  34881. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  34882. }
  34883. /**
  34884. * Adds a node class definition for the given type to the provided type library.
  34885. *
  34886. * @param {any} nodeClass - The node class definition.
  34887. * @param {number|string} type - The object type.
  34888. * @param {Map} library - The type library.
  34889. */
  34890. addType( nodeClass, type, library ) {
  34891. if ( library.has( type ) ) {
  34892. console.warn( `Redefinition of node ${ type }` );
  34893. return;
  34894. }
  34895. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  34896. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  34897. library.set( type, nodeClass );
  34898. }
  34899. /**
  34900. * Adds a node class definition for the given class definition to the provided type library.
  34901. *
  34902. * @param {any} nodeClass - The node class definition.
  34903. * @param {any} baseClass - The class definition.
  34904. * @param {WeakMap} library - The type library.
  34905. */
  34906. addClass( nodeClass, baseClass, library ) {
  34907. if ( library.has( baseClass ) ) {
  34908. console.warn( `Redefinition of node ${ baseClass.name }` );
  34909. return;
  34910. }
  34911. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  34912. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  34913. library.set( baseClass, nodeClass );
  34914. }
  34915. }
  34916. const _defaultLights = /*@__PURE__*/ new LightsNode();
  34917. const _chainKeys = [];
  34918. /**
  34919. * This renderer module manages the lights nodes which are unique
  34920. * per scene and camera combination.
  34921. *
  34922. * The lights node itself is later configured in the render list
  34923. * with the actual lights from the scene.
  34924. *
  34925. * @private
  34926. * @augments ChainMap
  34927. */
  34928. class Lighting extends ChainMap {
  34929. /**
  34930. * Constructs a lighting management component.
  34931. */
  34932. constructor() {
  34933. super();
  34934. }
  34935. /**
  34936. * Creates a new lights node for the given array of lights.
  34937. *
  34938. * @param {Array<Light>} lights - The render object.
  34939. * @return {LightsNode} The lights node.
  34940. */
  34941. createNode( lights = [] ) {
  34942. return new LightsNode().setLights( lights );
  34943. }
  34944. /**
  34945. * Returns a lights node for the given scene and camera.
  34946. *
  34947. * @param {Scene} scene - The scene.
  34948. * @param {Camera} camera - The camera.
  34949. * @return {LightsNode} The lights node.
  34950. */
  34951. getNode( scene, camera ) {
  34952. // ignore post-processing
  34953. if ( scene.isQuadMesh ) return _defaultLights;
  34954. _chainKeys[ 0 ] = scene;
  34955. _chainKeys[ 1 ] = camera;
  34956. let node = this.get( _chainKeys );
  34957. if ( node === undefined ) {
  34958. node = this.createNode();
  34959. this.set( _chainKeys, node );
  34960. }
  34961. _chainKeys.length = 0;
  34962. return node;
  34963. }
  34964. }
  34965. /**
  34966. * A special type of render target that is used when rendering
  34967. * with the WebXR Device API.
  34968. *
  34969. * @private
  34970. * @augments RenderTarget
  34971. */
  34972. class XRRenderTarget extends RenderTarget {
  34973. /**
  34974. * Constructs a new XR render target.
  34975. *
  34976. * @param {number} [width=1] - The width of the render target.
  34977. * @param {number} [height=1] - The height of the render target.
  34978. * @param {Object} [options={}] - The configuration options.
  34979. */
  34980. constructor( width = 1, height = 1, options = {} ) {
  34981. super( width, height, options );
  34982. /**
  34983. * This flag can be used for type testing.
  34984. *
  34985. * @type {boolean}
  34986. * @readonly
  34987. * @default true
  34988. */
  34989. this.isXRRenderTarget = true;
  34990. /**
  34991. * Whether the attachments of the render target
  34992. * are defined by external textures. This flag is
  34993. * set to `true` when using the WebXR Layers API.
  34994. *
  34995. * @type {boolean}
  34996. * @default false
  34997. */
  34998. this.hasExternalTextures = false;
  34999. /**
  35000. * Whether a depth buffer should automatically be allocated
  35001. * for this XR render target or not.
  35002. *
  35003. * Allocating a depth buffer is the default behavior of XR render
  35004. * targets. However, when using the WebXR Layers API, this flag
  35005. * must be set to `false` when the `ignoreDepthValues` property of
  35006. * the projection layers evaluates to `false`.
  35007. *
  35008. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  35009. *
  35010. * @type {boolean}
  35011. * @default true
  35012. */
  35013. this.autoAllocateDepthBuffer = true;
  35014. }
  35015. copy( source ) {
  35016. super.copy( source );
  35017. this.hasExternalTextures = source.hasExternalTextures;
  35018. this.autoAllocateDepthBuffer = source.autoAllocateDepthBuffer;
  35019. return this;
  35020. }
  35021. }
  35022. const _cameraLPos = /*@__PURE__*/ new Vector3();
  35023. const _cameraRPos = /*@__PURE__*/ new Vector3();
  35024. /**
  35025. * The XR manager is built on top of the WebXR Device API to
  35026. * manage XR sessions with `WebGPURenderer`.
  35027. *
  35028. * XR is currently only supported with a WebGL 2 backend.
  35029. *
  35030. * @augments EventDispatcher
  35031. */
  35032. class XRManager extends EventDispatcher {
  35033. /**
  35034. * Constructs a new XR manager.
  35035. *
  35036. * @param {Renderer} renderer - The renderer.
  35037. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  35038. */
  35039. constructor( renderer, multiview = false ) {
  35040. super();
  35041. /**
  35042. * This flag globally enables XR rendering.
  35043. *
  35044. * @type {boolean}
  35045. * @default false
  35046. */
  35047. this.enabled = false;
  35048. /**
  35049. * Whether the XR device is currently presenting or not.
  35050. *
  35051. * @type {boolean}
  35052. * @default false
  35053. * @readonly
  35054. */
  35055. this.isPresenting = false;
  35056. /**
  35057. * Whether the XR camera should automatically be updated or not.
  35058. *
  35059. * @type {boolean}
  35060. * @default true
  35061. */
  35062. this.cameraAutoUpdate = true;
  35063. /**
  35064. * The renderer.
  35065. *
  35066. * @private
  35067. * @type {Renderer}
  35068. */
  35069. this._renderer = renderer;
  35070. // camera
  35071. /**
  35072. * Represents the camera for the left eye.
  35073. *
  35074. * @private
  35075. * @type {PerspectiveCamera}
  35076. */
  35077. this._cameraL = new PerspectiveCamera();
  35078. this._cameraL.viewport = new Vector4();
  35079. /**
  35080. * Represents the camera for the right eye.
  35081. *
  35082. * @private
  35083. * @type {PerspectiveCamera}
  35084. */
  35085. this._cameraR = new PerspectiveCamera();
  35086. this._cameraR.viewport = new Vector4();
  35087. /**
  35088. * A list of cameras used for rendering the XR views.
  35089. *
  35090. * @private
  35091. * @type {Array<Camera>}
  35092. */
  35093. this._cameras = [ this._cameraL, this._cameraR ];
  35094. /**
  35095. * The main XR camera.
  35096. *
  35097. * @private
  35098. * @type {ArrayCamera}
  35099. */
  35100. this._cameraXR = new ArrayCamera();
  35101. /**
  35102. * The current near value of the XR camera.
  35103. *
  35104. * @private
  35105. * @type {?number}
  35106. * @default null
  35107. */
  35108. this._currentDepthNear = null;
  35109. /**
  35110. * The current far value of the XR camera.
  35111. *
  35112. * @private
  35113. * @type {?number}
  35114. * @default null
  35115. */
  35116. this._currentDepthFar = null;
  35117. /**
  35118. * A list of WebXR controllers requested by the application.
  35119. *
  35120. * @private
  35121. * @type {Array<WebXRController>}
  35122. */
  35123. this._controllers = [];
  35124. /**
  35125. * A list of XR input source. Each input source belongs to
  35126. * an instance of WebXRController.
  35127. *
  35128. * @private
  35129. * @type {Array<XRInputSource?>}
  35130. */
  35131. this._controllerInputSources = [];
  35132. /**
  35133. * The XR render target that represents the rendering destination
  35134. * during an active XR session.
  35135. *
  35136. * @private
  35137. * @type {?RenderTarget}
  35138. * @default null
  35139. */
  35140. this._xrRenderTarget = null;
  35141. /**
  35142. * An array holding all the non-projection layers
  35143. *
  35144. * @private
  35145. * @type {Array<Object>}
  35146. * @default []
  35147. */
  35148. this._layers = [];
  35149. /**
  35150. * Whether the device has support for all layer types.
  35151. *
  35152. * @type {boolean}
  35153. * @default false
  35154. */
  35155. this._supportsLayers = false;
  35156. /**
  35157. * Helper function to create native WebXR Layer.
  35158. *
  35159. * @private
  35160. * @type {Function}
  35161. */
  35162. this._createXRLayer = createXRLayer.bind( this );
  35163. /**
  35164. * The current WebGL context.
  35165. *
  35166. * @private
  35167. * @type {?WebGL2RenderingContext}
  35168. * @default null
  35169. */
  35170. this._gl = null;
  35171. /**
  35172. * The current animation context.
  35173. *
  35174. * @private
  35175. * @type {?Window}
  35176. * @default null
  35177. */
  35178. this._currentAnimationContext = null;
  35179. /**
  35180. * The current animation loop.
  35181. *
  35182. * @private
  35183. * @type {?Function}
  35184. * @default null
  35185. */
  35186. this._currentAnimationLoop = null;
  35187. /**
  35188. * The current pixel ratio.
  35189. *
  35190. * @private
  35191. * @type {?number}
  35192. * @default null
  35193. */
  35194. this._currentPixelRatio = null;
  35195. /**
  35196. * The current size of the renderer's canvas
  35197. * in logical pixel unit.
  35198. *
  35199. * @private
  35200. * @type {Vector2}
  35201. */
  35202. this._currentSize = new Vector2();
  35203. /**
  35204. * The default event listener for handling events inside a XR session.
  35205. *
  35206. * @private
  35207. * @type {Function}
  35208. */
  35209. this._onSessionEvent = onSessionEvent.bind( this );
  35210. /**
  35211. * The event listener for handling the end of a XR session.
  35212. *
  35213. * @private
  35214. * @type {Function}
  35215. */
  35216. this._onSessionEnd = onSessionEnd.bind( this );
  35217. /**
  35218. * The event listener for handling the `inputsourceschange` event.
  35219. *
  35220. * @private
  35221. * @type {Function}
  35222. */
  35223. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  35224. /**
  35225. * The animation loop which is used as a replacement for the default
  35226. * animation loop of the application. It is only used when a XR session
  35227. * is active.
  35228. *
  35229. * @private
  35230. * @type {Function}
  35231. */
  35232. this._onAnimationFrame = onAnimationFrame.bind( this );
  35233. /**
  35234. * The current XR reference space.
  35235. *
  35236. * @private
  35237. * @type {?XRReferenceSpace}
  35238. * @default null
  35239. */
  35240. this._referenceSpace = null;
  35241. /**
  35242. * The current XR reference space type.
  35243. *
  35244. * @private
  35245. * @type {XRReferenceSpaceType}
  35246. * @default 'local-floor'
  35247. */
  35248. this._referenceSpaceType = 'local-floor';
  35249. /**
  35250. * A custom reference space defined by the application.
  35251. *
  35252. * @private
  35253. * @type {?XRReferenceSpace}
  35254. * @default null
  35255. */
  35256. this._customReferenceSpace = null;
  35257. /**
  35258. * The framebuffer scale factor.
  35259. *
  35260. * @private
  35261. * @type {number}
  35262. * @default 1
  35263. */
  35264. this._framebufferScaleFactor = 1;
  35265. /**
  35266. * The foveation factor.
  35267. *
  35268. * @private
  35269. * @type {number}
  35270. * @default 1
  35271. */
  35272. this._foveation = 1.0;
  35273. /**
  35274. * A reference to the current XR session.
  35275. *
  35276. * @private
  35277. * @type {?XRSession}
  35278. * @default null
  35279. */
  35280. this._session = null;
  35281. /**
  35282. * A reference to the current XR base layer.
  35283. *
  35284. * @private
  35285. * @type {?XRWebGLLayer}
  35286. * @default null
  35287. */
  35288. this._glBaseLayer = null;
  35289. /**
  35290. * A reference to the current XR binding.
  35291. *
  35292. * @private
  35293. * @type {?XRWebGLBinding}
  35294. * @default null
  35295. */
  35296. this._glBinding = null;
  35297. /**
  35298. * A reference to the current XR projection layer.
  35299. *
  35300. * @private
  35301. * @type {?XRProjectionLayer}
  35302. * @default null
  35303. */
  35304. this._glProjLayer = null;
  35305. /**
  35306. * A reference to the current XR frame.
  35307. *
  35308. * @private
  35309. * @type {?XRFrame}
  35310. * @default null
  35311. */
  35312. this._xrFrame = null;
  35313. /**
  35314. * Whether to use the WebXR Layers API or not.
  35315. *
  35316. * @private
  35317. * @type {boolean}
  35318. * @readonly
  35319. */
  35320. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  35321. /**
  35322. * Whether the usage of multiview has been requested by the application or not.
  35323. *
  35324. * @private
  35325. * @type {boolean}
  35326. * @default false
  35327. * @readonly
  35328. */
  35329. this._useMultiviewIfPossible = multiview;
  35330. /**
  35331. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  35332. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  35333. *
  35334. * @private
  35335. * @type {boolean}
  35336. * @readonly
  35337. */
  35338. this._useMultiview = false;
  35339. }
  35340. /**
  35341. * Returns an instance of `THREE.Group` that represents the transformation
  35342. * of a XR controller in target ray space. The requested controller is defined
  35343. * by the given index.
  35344. *
  35345. * @param {number} index - The index of the XR controller.
  35346. * @return {Group} A group that represents the controller's transformation.
  35347. */
  35348. getController( index ) {
  35349. const controller = this._getController( index );
  35350. return controller.getTargetRaySpace();
  35351. }
  35352. /**
  35353. * Returns an instance of `THREE.Group` that represents the transformation
  35354. * of a XR controller in grip space. The requested controller is defined
  35355. * by the given index.
  35356. *
  35357. * @param {number} index - The index of the XR controller.
  35358. * @return {Group} A group that represents the controller's transformation.
  35359. */
  35360. getControllerGrip( index ) {
  35361. const controller = this._getController( index );
  35362. return controller.getGripSpace();
  35363. }
  35364. /**
  35365. * Returns an instance of `THREE.Group` that represents the transformation
  35366. * of a XR controller in hand space. The requested controller is defined
  35367. * by the given index.
  35368. *
  35369. * @param {number} index - The index of the XR controller.
  35370. * @return {Group} A group that represents the controller's transformation.
  35371. */
  35372. getHand( index ) {
  35373. const controller = this._getController( index );
  35374. return controller.getHandSpace();
  35375. }
  35376. /**
  35377. * Returns the foveation value.
  35378. *
  35379. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  35380. */
  35381. getFoveation() {
  35382. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  35383. return undefined;
  35384. }
  35385. return this._foveation;
  35386. }
  35387. /**
  35388. * Sets the foveation value.
  35389. *
  35390. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  35391. * and `1` means maximum foveation (the edges render at lower resolution).
  35392. */
  35393. setFoveation( foveation ) {
  35394. this._foveation = foveation;
  35395. if ( this._glProjLayer !== null ) {
  35396. this._glProjLayer.fixedFoveation = foveation;
  35397. }
  35398. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  35399. this._glBaseLayer.fixedFoveation = foveation;
  35400. }
  35401. }
  35402. /**
  35403. * Returns the framebuffer scale factor.
  35404. *
  35405. * @return {number} The framebuffer scale factor.
  35406. */
  35407. getFramebufferScaleFactor() {
  35408. return this._framebufferScaleFactor;
  35409. }
  35410. /**
  35411. * Sets the framebuffer scale factor.
  35412. *
  35413. * This method can not be used during a XR session.
  35414. *
  35415. * @param {number} factor - The framebuffer scale factor.
  35416. */
  35417. setFramebufferScaleFactor( factor ) {
  35418. this._framebufferScaleFactor = factor;
  35419. if ( this.isPresenting === true ) {
  35420. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  35421. }
  35422. }
  35423. /**
  35424. * Returns the reference space type.
  35425. *
  35426. * @return {XRReferenceSpaceType} The reference space type.
  35427. */
  35428. getReferenceSpaceType() {
  35429. return this._referenceSpaceType;
  35430. }
  35431. /**
  35432. * Sets the reference space type.
  35433. *
  35434. * This method can not be used during a XR session.
  35435. *
  35436. * @param {XRReferenceSpaceType} type - The reference space type.
  35437. */
  35438. setReferenceSpaceType( type ) {
  35439. this._referenceSpaceType = type;
  35440. if ( this.isPresenting === true ) {
  35441. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  35442. }
  35443. }
  35444. /**
  35445. * Returns the XR reference space.
  35446. *
  35447. * @return {XRReferenceSpace} The XR reference space.
  35448. */
  35449. getReferenceSpace() {
  35450. return this._customReferenceSpace || this._referenceSpace;
  35451. }
  35452. /**
  35453. * Sets a custom XR reference space.
  35454. *
  35455. * @param {XRReferenceSpace} space - The XR reference space.
  35456. */
  35457. setReferenceSpace( space ) {
  35458. this._customReferenceSpace = space;
  35459. }
  35460. /**
  35461. * Returns the XR camera.
  35462. *
  35463. * @return {ArrayCamera} The XR camera.
  35464. */
  35465. getCamera() {
  35466. return this._cameraXR;
  35467. }
  35468. /**
  35469. * Returns the environment blend mode from the current XR session.
  35470. *
  35471. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  35472. */
  35473. getEnvironmentBlendMode() {
  35474. if ( this._session !== null ) {
  35475. return this._session.environmentBlendMode;
  35476. }
  35477. }
  35478. /**
  35479. * Returns the current XR frame.
  35480. *
  35481. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  35482. */
  35483. getFrame() {
  35484. return this._xrFrame;
  35485. }
  35486. /**
  35487. * Returns `true` if the engine renders to a multiview target.
  35488. *
  35489. * @return {boolean} Whether the engine renders to a multiview render target or not.
  35490. */
  35491. useMultiview() {
  35492. return this._useMultiview;
  35493. }
  35494. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = [] ) {
  35495. const geometry = new PlaneGeometry( width, height );
  35496. const renderTarget = new XRRenderTarget(
  35497. pixelwidth,
  35498. pixelheight,
  35499. {
  35500. format: RGBAFormat,
  35501. type: UnsignedByteType,
  35502. depthTexture: new DepthTexture(
  35503. pixelwidth,
  35504. pixelheight,
  35505. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35506. undefined,
  35507. undefined,
  35508. undefined,
  35509. undefined,
  35510. undefined,
  35511. undefined,
  35512. attributes.stencil ? DepthStencilFormat : DepthFormat
  35513. ),
  35514. stencilBuffer: attributes.stencil,
  35515. resolveDepthBuffer: false,
  35516. resolveStencilBuffer: false
  35517. } );
  35518. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  35519. material.map = renderTarget.texture;
  35520. material.map.offset.y = 1;
  35521. material.map.repeat.y = -1;
  35522. const plane = new Mesh( geometry, material );
  35523. plane.position.copy( translation );
  35524. plane.quaternion.copy( quaternion );
  35525. const layer = {
  35526. type: 'quad',
  35527. width: width,
  35528. height: height,
  35529. translation: translation,
  35530. quaternion: quaternion,
  35531. pixelwidth: pixelwidth,
  35532. pixelheight: pixelheight,
  35533. plane: plane,
  35534. material: material,
  35535. rendercall: rendercall,
  35536. renderTarget: renderTarget };
  35537. this._layers.push( layer );
  35538. if ( this._session !== null ) {
  35539. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  35540. layer.plane.material.blending = CustomBlending;
  35541. layer.plane.material.blendEquation = AddEquation;
  35542. layer.plane.material.blendSrc = ZeroFactor;
  35543. layer.plane.material.blendDst = ZeroFactor;
  35544. layer.xrlayer = this._createXRLayer( layer );
  35545. const xrlayers = this._session.renderState.layers;
  35546. xrlayers.unshift( layer.xrlayer );
  35547. this._session.updateRenderState( { layers: xrlayers } );
  35548. } else {
  35549. renderTarget.isXRRenderTarget = false;
  35550. }
  35551. return plane;
  35552. }
  35553. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = [] ) {
  35554. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  35555. const renderTarget = new XRRenderTarget(
  35556. pixelwidth,
  35557. pixelheight,
  35558. {
  35559. format: RGBAFormat,
  35560. type: UnsignedByteType,
  35561. depthTexture: new DepthTexture(
  35562. pixelwidth,
  35563. pixelheight,
  35564. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35565. undefined,
  35566. undefined,
  35567. undefined,
  35568. undefined,
  35569. undefined,
  35570. undefined,
  35571. attributes.stencil ? DepthStencilFormat : DepthFormat
  35572. ),
  35573. stencilBuffer: attributes.stencil,
  35574. resolveDepthBuffer: false,
  35575. resolveStencilBuffer: false
  35576. } );
  35577. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  35578. material.map = renderTarget.texture;
  35579. material.map.offset.y = 1;
  35580. material.map.repeat.y = -1;
  35581. const plane = new Mesh( geometry, material );
  35582. plane.position.copy( translation );
  35583. plane.quaternion.copy( quaternion );
  35584. const layer = {
  35585. type: 'cylinder',
  35586. radius: radius,
  35587. centralAngle: centralAngle,
  35588. aspectratio: aspectratio,
  35589. translation: translation,
  35590. quaternion: quaternion,
  35591. pixelwidth: pixelwidth,
  35592. pixelheight: pixelheight,
  35593. plane: plane,
  35594. material: material,
  35595. rendercall: rendercall,
  35596. renderTarget: renderTarget };
  35597. this._layers.push( layer );
  35598. if ( this._session !== null ) {
  35599. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  35600. layer.plane.material.blending = CustomBlending;
  35601. layer.plane.material.blendEquation = AddEquation;
  35602. layer.plane.material.blendSrc = ZeroFactor;
  35603. layer.plane.material.blendDst = ZeroFactor;
  35604. layer.xrlayer = this._createXRLayer( layer );
  35605. const xrlayers = this._session.renderState.layers;
  35606. xrlayers.unshift( layer.xrlayer );
  35607. this._session.updateRenderState( { layers: xrlayers } );
  35608. } else {
  35609. renderTarget.isXRRenderTarget = false;
  35610. }
  35611. return plane;
  35612. }
  35613. renderLayers( ) {
  35614. const translationObject = new Vector3();
  35615. const quaternionObject = new Quaternion();
  35616. const wasPresenting = this.isPresenting;
  35617. this.isPresenting = false;
  35618. for ( const layer of this._layers ) {
  35619. layer.renderTarget.isXRRenderTarget = this._session !== null;
  35620. layer.renderTarget.hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  35621. layer.renderTarget.autoAllocateDepthBuffer = ! layer.renderTarget.isXRRenderTarget;
  35622. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  35623. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  35624. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  35625. this._renderer.backend.setXRRenderTargetTextures(
  35626. layer.renderTarget,
  35627. glSubImage.colorTexture,
  35628. glSubImage.depthStencilTexture );
  35629. }
  35630. this._renderer.setRenderTarget( layer.renderTarget );
  35631. layer.rendercall();
  35632. }
  35633. this.isPresenting = wasPresenting;
  35634. this._renderer.setRenderTarget( null );
  35635. }
  35636. /**
  35637. * Returns the current XR session.
  35638. *
  35639. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  35640. */
  35641. getSession() {
  35642. return this._session;
  35643. }
  35644. /**
  35645. * After a XR session has been requested usually with one of the `*Button` modules, it
  35646. * is injected into the renderer with this method. This method triggers the start of
  35647. * the actual XR rendering.
  35648. *
  35649. * @async
  35650. * @param {XRSession} session - The XR session to set.
  35651. * @return {Promise} A Promise that resolves when the session has been set.
  35652. */
  35653. async setSession( session ) {
  35654. const renderer = this._renderer;
  35655. const backend = renderer.backend;
  35656. this._gl = renderer.getContext();
  35657. const gl = this._gl;
  35658. const attributes = gl.getContextAttributes();
  35659. this._session = session;
  35660. if ( session !== null ) {
  35661. if ( backend.isWebGPUBackend === true ) throw new Error( 'THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.' );
  35662. session.addEventListener( 'select', this._onSessionEvent );
  35663. session.addEventListener( 'selectstart', this._onSessionEvent );
  35664. session.addEventListener( 'selectend', this._onSessionEvent );
  35665. session.addEventListener( 'squeeze', this._onSessionEvent );
  35666. session.addEventListener( 'squeezestart', this._onSessionEvent );
  35667. session.addEventListener( 'squeezeend', this._onSessionEvent );
  35668. session.addEventListener( 'end', this._onSessionEnd );
  35669. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  35670. await backend.makeXRCompatible();
  35671. this._currentPixelRatio = renderer.getPixelRatio();
  35672. renderer.getSize( this._currentSize );
  35673. this._currentAnimationContext = renderer._animation.getContext();
  35674. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  35675. renderer._animation.stop();
  35676. //
  35677. if ( this._useLayers === true ) {
  35678. // default path using XRWebGLBinding/XRProjectionLayer
  35679. let depthFormat = null;
  35680. let depthType = null;
  35681. let glDepthFormat = null;
  35682. if ( renderer.depth ) {
  35683. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  35684. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  35685. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  35686. }
  35687. const projectionlayerInit = {
  35688. colorFormat: gl.RGBA8,
  35689. depthFormat: glDepthFormat,
  35690. scaleFactor: this._framebufferScaleFactor
  35691. };
  35692. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  35693. projectionlayerInit.textureType = 'texture-array';
  35694. this._useMultiview = true;
  35695. }
  35696. const glBinding = new XRWebGLBinding( session, gl );
  35697. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  35698. const layersArray = [ glProjLayer ];
  35699. this._glBinding = glBinding;
  35700. this._glProjLayer = glProjLayer;
  35701. renderer.setPixelRatio( 1 );
  35702. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  35703. let depthTexture;
  35704. if ( this._useMultiview ) {
  35705. depthTexture = new DepthArrayTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, 2 );
  35706. depthTexture.type = depthType;
  35707. depthTexture.format = depthFormat;
  35708. } else {
  35709. depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat );
  35710. }
  35711. this._xrRenderTarget = new XRRenderTarget(
  35712. glProjLayer.textureWidth,
  35713. glProjLayer.textureHeight,
  35714. {
  35715. format: RGBAFormat,
  35716. type: UnsignedByteType,
  35717. colorSpace: renderer.outputColorSpace,
  35718. depthTexture: depthTexture,
  35719. stencilBuffer: renderer.stencil,
  35720. samples: attributes.antialias ? 4 : 0,
  35721. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  35722. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  35723. depth: this._useMultiview ? 2 : 1,
  35724. multiview: this._useMultiview
  35725. } );
  35726. this._xrRenderTarget.hasExternalTextures = true;
  35727. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  35728. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  35729. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  35730. if ( this._supportsLayers ) {
  35731. // switch layers to native
  35732. for ( const layer of this._layers ) {
  35733. // change material so it "punches" out a hole to show the XR Layer.
  35734. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  35735. layer.plane.material.blending = CustomBlending;
  35736. layer.plane.material.blendEquation = AddEquation;
  35737. layer.plane.material.blendSrc = ZeroFactor;
  35738. layer.plane.material.blendDst = ZeroFactor;
  35739. layer.xrlayer = this._createXRLayer( layer );
  35740. layersArray.unshift( layer.xrlayer );
  35741. }
  35742. }
  35743. session.updateRenderState( { layers: layersArray } );
  35744. } else {
  35745. // fallback to XRWebGLLayer
  35746. const layerInit = {
  35747. antialias: renderer.samples > 0,
  35748. alpha: true,
  35749. depth: renderer.depth,
  35750. stencil: renderer.stencil,
  35751. framebufferScaleFactor: this.getFramebufferScaleFactor()
  35752. };
  35753. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  35754. this._glBaseLayer = glBaseLayer;
  35755. session.updateRenderState( { baseLayer: glBaseLayer } );
  35756. renderer.setPixelRatio( 1 );
  35757. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  35758. this._xrRenderTarget = new XRRenderTarget(
  35759. glBaseLayer.framebufferWidth,
  35760. glBaseLayer.framebufferHeight,
  35761. {
  35762. format: RGBAFormat,
  35763. type: UnsignedByteType,
  35764. colorSpace: renderer.outputColorSpace,
  35765. stencilBuffer: renderer.stencil,
  35766. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  35767. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  35768. }
  35769. );
  35770. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  35771. }
  35772. //
  35773. this.setFoveation( this.getFoveation() );
  35774. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  35775. renderer._animation.setContext( session );
  35776. renderer._animation.start();
  35777. this.isPresenting = true;
  35778. this.dispatchEvent( { type: 'sessionstart' } );
  35779. }
  35780. }
  35781. /**
  35782. * This method is called by the renderer per frame and updates the XR camera
  35783. * and it sub cameras based on the given camera. The given camera is the "user"
  35784. * camera created on application level and used for non-XR rendering.
  35785. *
  35786. * @param {PerspectiveCamera} camera - The camera.
  35787. */
  35788. updateCamera( camera ) {
  35789. const session = this._session;
  35790. if ( session === null ) return;
  35791. const depthNear = camera.near;
  35792. const depthFar = camera.far;
  35793. const cameraXR = this._cameraXR;
  35794. const cameraL = this._cameraL;
  35795. const cameraR = this._cameraR;
  35796. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  35797. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  35798. cameraXR.isMultiViewCamera = this._useMultiview;
  35799. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  35800. // Note that the new renderState won't apply until the next frame. See #18320
  35801. session.updateRenderState( {
  35802. depthNear: cameraXR.near,
  35803. depthFar: cameraXR.far
  35804. } );
  35805. this._currentDepthNear = cameraXR.near;
  35806. this._currentDepthFar = cameraXR.far;
  35807. }
  35808. cameraL.layers.mask = camera.layers.mask | 0b010;
  35809. cameraR.layers.mask = camera.layers.mask | 0b100;
  35810. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  35811. const parent = camera.parent;
  35812. const cameras = cameraXR.cameras;
  35813. updateCamera( cameraXR, parent );
  35814. for ( let i = 0; i < cameras.length; i ++ ) {
  35815. updateCamera( cameras[ i ], parent );
  35816. }
  35817. // update projection matrix for proper view frustum culling
  35818. if ( cameras.length === 2 ) {
  35819. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  35820. } else {
  35821. // assume single camera setup (AR)
  35822. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  35823. }
  35824. // update user camera and its children
  35825. updateUserCamera( camera, cameraXR, parent );
  35826. }
  35827. /**
  35828. * Returns a WebXR controller for the given controller index.
  35829. *
  35830. * @private
  35831. * @param {number} index - The controller index.
  35832. * @return {WebXRController} The XR controller.
  35833. */
  35834. _getController( index ) {
  35835. let controller = this._controllers[ index ];
  35836. if ( controller === undefined ) {
  35837. controller = new WebXRController();
  35838. this._controllers[ index ] = controller;
  35839. }
  35840. return controller;
  35841. }
  35842. }
  35843. /**
  35844. * Assumes 2 cameras that are parallel and share an X-axis, and that
  35845. * the cameras' projection and world matrices have already been set.
  35846. * And that near and far planes are identical for both cameras.
  35847. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  35848. *
  35849. * @param {ArrayCamera} camera - The camera to update.
  35850. * @param {PerspectiveCamera} cameraL - The left camera.
  35851. * @param {PerspectiveCamera} cameraR - The right camera.
  35852. */
  35853. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  35854. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  35855. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  35856. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  35857. const projL = cameraL.projectionMatrix.elements;
  35858. const projR = cameraR.projectionMatrix.elements;
  35859. // VR systems will have identical far and near planes, and
  35860. // most likely identical top and bottom frustum extents.
  35861. // Use the left camera for these values.
  35862. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  35863. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  35864. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  35865. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  35866. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  35867. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  35868. const left = near * leftFov;
  35869. const right = near * rightFov;
  35870. // Calculate the new camera's position offset from the
  35871. // left camera. xOffset should be roughly half `ipd`.
  35872. const zOffset = ipd / ( - leftFov + rightFov );
  35873. const xOffset = zOffset * - leftFov;
  35874. // TODO: Better way to apply this offset?
  35875. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  35876. camera.translateX( xOffset );
  35877. camera.translateZ( zOffset );
  35878. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  35879. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  35880. // Check if the projection uses an infinite far plane.
  35881. if ( projL[ 10 ] === -1 ) {
  35882. // Use the projection matrix from the left eye.
  35883. // The camera offset is sufficient to include the view volumes
  35884. // of both eyes (assuming symmetric projections).
  35885. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  35886. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  35887. } else {
  35888. // Find the union of the frustum values of the cameras and scale
  35889. // the values so that the near plane's position does not change in world space,
  35890. // although must now be relative to the new union camera.
  35891. const near2 = near + zOffset;
  35892. const far2 = far + zOffset;
  35893. const left2 = left - xOffset;
  35894. const right2 = right + ( ipd - xOffset );
  35895. const top2 = topFov * far / far2 * near2;
  35896. const bottom2 = bottomFov * far / far2 * near2;
  35897. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  35898. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  35899. }
  35900. }
  35901. /**
  35902. * Updates the world matrices for the given camera based on the parent 3D object.
  35903. *
  35904. * @inner
  35905. * @param {Camera} camera - The camera to update.
  35906. * @param {Object3D} parent - The parent 3D object.
  35907. */
  35908. function updateCamera( camera, parent ) {
  35909. if ( parent === null ) {
  35910. camera.matrixWorld.copy( camera.matrix );
  35911. } else {
  35912. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  35913. }
  35914. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  35915. }
  35916. /**
  35917. * Updates the given camera with the transformation of the XR camera and parent object.
  35918. *
  35919. * @inner
  35920. * @param {Camera} camera - The camera to update.
  35921. * @param {ArrayCamera} cameraXR - The XR camera.
  35922. * @param {Object3D} parent - The parent 3D object.
  35923. */
  35924. function updateUserCamera( camera, cameraXR, parent ) {
  35925. if ( parent === null ) {
  35926. camera.matrix.copy( cameraXR.matrixWorld );
  35927. } else {
  35928. camera.matrix.copy( parent.matrixWorld );
  35929. camera.matrix.invert();
  35930. camera.matrix.multiply( cameraXR.matrixWorld );
  35931. }
  35932. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  35933. camera.updateMatrixWorld( true );
  35934. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  35935. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  35936. if ( camera.isPerspectiveCamera ) {
  35937. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  35938. camera.zoom = 1;
  35939. }
  35940. }
  35941. function onSessionEvent( event ) {
  35942. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  35943. if ( controllerIndex === -1 ) {
  35944. return;
  35945. }
  35946. const controller = this._controllers[ controllerIndex ];
  35947. if ( controller !== undefined ) {
  35948. const referenceSpace = this.getReferenceSpace();
  35949. controller.update( event.inputSource, event.frame, referenceSpace );
  35950. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  35951. }
  35952. }
  35953. function onSessionEnd() {
  35954. const session = this._session;
  35955. const renderer = this._renderer;
  35956. session.removeEventListener( 'select', this._onSessionEvent );
  35957. session.removeEventListener( 'selectstart', this._onSessionEvent );
  35958. session.removeEventListener( 'selectend', this._onSessionEvent );
  35959. session.removeEventListener( 'squeeze', this._onSessionEvent );
  35960. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  35961. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  35962. session.removeEventListener( 'end', this._onSessionEnd );
  35963. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  35964. for ( let i = 0; i < this._controllers.length; i ++ ) {
  35965. const inputSource = this._controllerInputSources[ i ];
  35966. if ( inputSource === null ) continue;
  35967. this._controllerInputSources[ i ] = null;
  35968. this._controllers[ i ].disconnect( inputSource );
  35969. }
  35970. this._currentDepthNear = null;
  35971. this._currentDepthFar = null;
  35972. // restore framebuffer/rendering state
  35973. renderer.backend.setXRTarget( null );
  35974. renderer.setOutputRenderTarget( null );
  35975. renderer.setRenderTarget( null );
  35976. this._session = null;
  35977. this._xrRenderTarget = null;
  35978. // switch layers back to emulated
  35979. if ( this._supportsLayers === true ) {
  35980. for ( const layer of this._layers ) {
  35981. // Recreate layer render target to reset state
  35982. layer.renderTarget = new XRRenderTarget(
  35983. layer.pixelwidth,
  35984. layer.pixelheight,
  35985. {
  35986. format: RGBAFormat,
  35987. type: UnsignedByteType,
  35988. depthTexture: new DepthTexture(
  35989. layer.pixelwidth,
  35990. layer.pixelheight,
  35991. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  35992. undefined,
  35993. undefined,
  35994. undefined,
  35995. undefined,
  35996. undefined,
  35997. undefined,
  35998. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  35999. ),
  36000. stencilBuffer: layer.stencilBuffer,
  36001. resolveDepthBuffer: false,
  36002. resolveStencilBuffer: false
  36003. } );
  36004. layer.renderTarget.isXRRenderTarget = false;
  36005. layer.plane.material = layer.material;
  36006. layer.material.map = layer.renderTarget.texture;
  36007. delete layer.xrlayer;
  36008. }
  36009. }
  36010. //
  36011. this.isPresenting = false;
  36012. this._useMultiview = false;
  36013. renderer._animation.stop();
  36014. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  36015. renderer._animation.setContext( this._currentAnimationContext );
  36016. renderer._animation.start();
  36017. renderer.setPixelRatio( this._currentPixelRatio );
  36018. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  36019. this.dispatchEvent( { type: 'sessionend' } );
  36020. }
  36021. function onInputSourcesChange( event ) {
  36022. const controllers = this._controllers;
  36023. const controllerInputSources = this._controllerInputSources;
  36024. // Notify disconnected
  36025. for ( let i = 0; i < event.removed.length; i ++ ) {
  36026. const inputSource = event.removed[ i ];
  36027. const index = controllerInputSources.indexOf( inputSource );
  36028. if ( index >= 0 ) {
  36029. controllerInputSources[ index ] = null;
  36030. controllers[ index ].disconnect( inputSource );
  36031. }
  36032. }
  36033. // Notify connected
  36034. for ( let i = 0; i < event.added.length; i ++ ) {
  36035. const inputSource = event.added[ i ];
  36036. let controllerIndex = controllerInputSources.indexOf( inputSource );
  36037. if ( controllerIndex === -1 ) {
  36038. // Assign input source a controller that currently has no input source
  36039. for ( let i = 0; i < controllers.length; i ++ ) {
  36040. if ( i >= controllerInputSources.length ) {
  36041. controllerInputSources.push( inputSource );
  36042. controllerIndex = i;
  36043. break;
  36044. } else if ( controllerInputSources[ i ] === null ) {
  36045. controllerInputSources[ i ] = inputSource;
  36046. controllerIndex = i;
  36047. break;
  36048. }
  36049. }
  36050. // If all controllers do currently receive input we ignore new ones
  36051. if ( controllerIndex === -1 ) break;
  36052. }
  36053. const controller = controllers[ controllerIndex ];
  36054. if ( controller ) {
  36055. controller.connect( inputSource );
  36056. }
  36057. }
  36058. }
  36059. // Creation method for native WebXR layers
  36060. function createXRLayer( layer ) {
  36061. if ( layer.type === 'quad' ) {
  36062. return this._glBinding.createQuadLayer( {
  36063. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36064. depthFormat: this._gl.DEPTH_COMPONENT,
  36065. width: layer.width / 2,
  36066. height: layer.height / 2,
  36067. space: this._referenceSpace,
  36068. viewPixelWidth: layer.pixelwidth,
  36069. viewPixelHeight: layer.pixelheight
  36070. } );
  36071. } else {
  36072. return this._glBinding.createCylinderLayer( {
  36073. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36074. depthFormat: this._gl.DEPTH_COMPONENT,
  36075. radius: layer.radius,
  36076. centralAngle: layer.centralAngle,
  36077. aspectRatio: layer.aspectRatio,
  36078. space: this._referenceSpace,
  36079. viewPixelWidth: layer.pixelwidth,
  36080. viewPixelHeight: layer.pixelheight
  36081. } );
  36082. }
  36083. }
  36084. // Animation Loop
  36085. function onAnimationFrame( time, frame ) {
  36086. if ( frame === undefined ) return;
  36087. const cameraXR = this._cameraXR;
  36088. const renderer = this._renderer;
  36089. const backend = renderer.backend;
  36090. const glBaseLayer = this._glBaseLayer;
  36091. const referenceSpace = this.getReferenceSpace();
  36092. const pose = frame.getViewerPose( referenceSpace );
  36093. this._xrFrame = frame;
  36094. if ( pose !== null ) {
  36095. const views = pose.views;
  36096. if ( this._glBaseLayer !== null ) {
  36097. backend.setXRTarget( glBaseLayer.framebuffer );
  36098. }
  36099. let cameraXRNeedsUpdate = false;
  36100. // check if it's necessary to rebuild cameraXR's camera list
  36101. if ( views.length !== cameraXR.cameras.length ) {
  36102. cameraXR.cameras.length = 0;
  36103. cameraXRNeedsUpdate = true;
  36104. }
  36105. for ( let i = 0; i < views.length; i ++ ) {
  36106. const view = views[ i ];
  36107. let viewport;
  36108. if ( this._useLayers === true ) {
  36109. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  36110. viewport = glSubImage.viewport;
  36111. // For side-by-side projection, we only produce a single texture for both eyes.
  36112. if ( i === 0 ) {
  36113. backend.setXRRenderTargetTextures(
  36114. this._xrRenderTarget,
  36115. glSubImage.colorTexture,
  36116. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  36117. );
  36118. }
  36119. } else {
  36120. viewport = glBaseLayer.getViewport( view );
  36121. }
  36122. let camera = this._cameras[ i ];
  36123. if ( camera === undefined ) {
  36124. camera = new PerspectiveCamera();
  36125. camera.layers.enable( i );
  36126. camera.viewport = new Vector4();
  36127. this._cameras[ i ] = camera;
  36128. }
  36129. camera.matrix.fromArray( view.transform.matrix );
  36130. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36131. camera.projectionMatrix.fromArray( view.projectionMatrix );
  36132. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36133. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  36134. if ( i === 0 ) {
  36135. cameraXR.matrix.copy( camera.matrix );
  36136. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  36137. }
  36138. if ( cameraXRNeedsUpdate === true ) {
  36139. cameraXR.cameras.push( camera );
  36140. }
  36141. }
  36142. renderer.setOutputRenderTarget( this._xrRenderTarget );
  36143. }
  36144. //
  36145. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36146. const inputSource = this._controllerInputSources[ i ];
  36147. const controller = this._controllers[ i ];
  36148. if ( inputSource !== null && controller !== undefined ) {
  36149. controller.update( inputSource, frame, referenceSpace );
  36150. }
  36151. }
  36152. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  36153. if ( frame.detectedPlanes ) {
  36154. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  36155. }
  36156. this._xrFrame = null;
  36157. }
  36158. const _scene = /*@__PURE__*/ new Scene();
  36159. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  36160. const _screen = /*@__PURE__*/ new Vector4();
  36161. const _frustum = /*@__PURE__*/ new Frustum();
  36162. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  36163. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  36164. const _vector4 = /*@__PURE__*/ new Vector4();
  36165. /**
  36166. * Base class for renderers.
  36167. */
  36168. class Renderer {
  36169. /**
  36170. * Renderer options.
  36171. *
  36172. * @typedef {Object} Renderer~Options
  36173. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  36174. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  36175. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  36176. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  36177. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  36178. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  36179. * to overwrite the default.
  36180. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36181. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  36182. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  36183. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  36184. */
  36185. /**
  36186. * Constructs a new renderer.
  36187. *
  36188. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  36189. * @param {Renderer~Options} [parameters] - The configuration parameter.
  36190. */
  36191. constructor( backend, parameters = {} ) {
  36192. /**
  36193. * This flag can be used for type testing.
  36194. *
  36195. * @type {boolean}
  36196. * @readonly
  36197. * @default true
  36198. */
  36199. this.isRenderer = true;
  36200. //
  36201. const {
  36202. logarithmicDepthBuffer = false,
  36203. alpha = true,
  36204. depth = true,
  36205. stencil = false,
  36206. antialias = false,
  36207. samples = 0,
  36208. getFallback = null,
  36209. colorBufferType = HalfFloatType,
  36210. multiview = false
  36211. } = parameters;
  36212. /**
  36213. * A reference to the canvas element the renderer is drawing to.
  36214. * This value of this property will automatically be created by
  36215. * the renderer.
  36216. *
  36217. * @type {HTMLCanvasElement|OffscreenCanvas}
  36218. */
  36219. this.domElement = backend.getDomElement();
  36220. /**
  36221. * A reference to the current backend.
  36222. *
  36223. * @type {Backend}
  36224. */
  36225. this.backend = backend;
  36226. /**
  36227. * The number of MSAA samples.
  36228. *
  36229. * @type {number}
  36230. * @default 0
  36231. */
  36232. this.samples = samples || ( antialias === true ) ? 4 : 0;
  36233. /**
  36234. * Whether the renderer should automatically clear the current rendering target
  36235. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  36236. * or the current bound render target (custom framebuffer).
  36237. *
  36238. * @type {boolean}
  36239. * @default true
  36240. */
  36241. this.autoClear = true;
  36242. /**
  36243. * When `autoClear` is set to `true`, this property defines whether the renderer
  36244. * should clear the color buffer.
  36245. *
  36246. * @type {boolean}
  36247. * @default true
  36248. */
  36249. this.autoClearColor = true;
  36250. /**
  36251. * When `autoClear` is set to `true`, this property defines whether the renderer
  36252. * should clear the depth buffer.
  36253. *
  36254. * @type {boolean}
  36255. * @default true
  36256. */
  36257. this.autoClearDepth = true;
  36258. /**
  36259. * When `autoClear` is set to `true`, this property defines whether the renderer
  36260. * should clear the stencil buffer.
  36261. *
  36262. * @type {boolean}
  36263. * @default true
  36264. */
  36265. this.autoClearStencil = true;
  36266. /**
  36267. * Whether the default framebuffer should be transparent or opaque.
  36268. *
  36269. * @type {boolean}
  36270. * @default true
  36271. */
  36272. this.alpha = alpha;
  36273. /**
  36274. * Whether logarithmic depth buffer is enabled or not.
  36275. *
  36276. * @type {boolean}
  36277. * @default false
  36278. */
  36279. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  36280. /**
  36281. * Defines the output color space of the renderer.
  36282. *
  36283. * @type {string}
  36284. * @default SRGBColorSpace
  36285. */
  36286. this.outputColorSpace = SRGBColorSpace;
  36287. /**
  36288. * Defines the tone mapping of the renderer.
  36289. *
  36290. * @type {number}
  36291. * @default NoToneMapping
  36292. */
  36293. this.toneMapping = NoToneMapping;
  36294. /**
  36295. * Defines the tone mapping exposure.
  36296. *
  36297. * @type {number}
  36298. * @default 1
  36299. */
  36300. this.toneMappingExposure = 1.0;
  36301. /**
  36302. * Whether the renderer should sort its render lists or not.
  36303. *
  36304. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  36305. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  36306. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  36307. * e.g. manually determining each object's rendering order.
  36308. *
  36309. * @type {boolean}
  36310. * @default true
  36311. */
  36312. this.sortObjects = true;
  36313. /**
  36314. * Whether the default framebuffer should have a depth buffer or not.
  36315. *
  36316. * @type {boolean}
  36317. * @default true
  36318. */
  36319. this.depth = depth;
  36320. /**
  36321. * Whether the default framebuffer should have a stencil buffer or not.
  36322. *
  36323. * @type {boolean}
  36324. * @default false
  36325. */
  36326. this.stencil = stencil;
  36327. /**
  36328. * Holds a series of statistical information about the GPU memory
  36329. * and the rendering process. Useful for debugging and monitoring.
  36330. *
  36331. * @type {Info}
  36332. */
  36333. this.info = new Info();
  36334. /**
  36335. * Stores override nodes for specific transformations or calculations.
  36336. * These nodes can be used to replace default behavior in the rendering pipeline.
  36337. *
  36338. * @type {Object}
  36339. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  36340. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  36341. */
  36342. this.overrideNodes = {
  36343. modelViewMatrix: null,
  36344. modelNormalViewMatrix: null
  36345. };
  36346. /**
  36347. * The node library defines how certain library objects like materials, lights
  36348. * or tone mapping functions are mapped to node types. This is required since
  36349. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  36350. * be part of the scene graph, they are internally represented as nodes for
  36351. * further processing.
  36352. *
  36353. * @type {NodeLibrary}
  36354. */
  36355. this.library = new NodeLibrary();
  36356. /**
  36357. * A map-like data structure for managing lights.
  36358. *
  36359. * @type {Lighting}
  36360. */
  36361. this.lighting = new Lighting();
  36362. // internals
  36363. /**
  36364. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36365. *
  36366. * @private
  36367. * @type {?Function}
  36368. */
  36369. this._getFallback = getFallback;
  36370. /**
  36371. * The renderer's pixel ratio.
  36372. *
  36373. * @private
  36374. * @type {number}
  36375. * @default 1
  36376. */
  36377. this._pixelRatio = 1;
  36378. /**
  36379. * The width of the renderer's default framebuffer in logical pixel unit.
  36380. *
  36381. * @private
  36382. * @type {number}
  36383. */
  36384. this._width = this.domElement.width;
  36385. /**
  36386. * The height of the renderer's default framebuffer in logical pixel unit.
  36387. *
  36388. * @private
  36389. * @type {number}
  36390. */
  36391. this._height = this.domElement.height;
  36392. /**
  36393. * The viewport of the renderer in logical pixel unit.
  36394. *
  36395. * @private
  36396. * @type {Vector4}
  36397. */
  36398. this._viewport = new Vector4( 0, 0, this._width, this._height );
  36399. /**
  36400. * The scissor rectangle of the renderer in logical pixel unit.
  36401. *
  36402. * @private
  36403. * @type {Vector4}
  36404. */
  36405. this._scissor = new Vector4( 0, 0, this._width, this._height );
  36406. /**
  36407. * Whether the scissor test should be enabled or not.
  36408. *
  36409. * @private
  36410. * @type {boolean}
  36411. */
  36412. this._scissorTest = false;
  36413. /**
  36414. * A reference to a renderer module for managing shader attributes.
  36415. *
  36416. * @private
  36417. * @type {?Attributes}
  36418. * @default null
  36419. */
  36420. this._attributes = null;
  36421. /**
  36422. * A reference to a renderer module for managing geometries.
  36423. *
  36424. * @private
  36425. * @type {?Geometries}
  36426. * @default null
  36427. */
  36428. this._geometries = null;
  36429. /**
  36430. * A reference to a renderer module for managing node related logic.
  36431. *
  36432. * @private
  36433. * @type {?Nodes}
  36434. * @default null
  36435. */
  36436. this._nodes = null;
  36437. /**
  36438. * A reference to a renderer module for managing the internal animation loop.
  36439. *
  36440. * @private
  36441. * @type {?Animation}
  36442. * @default null
  36443. */
  36444. this._animation = null;
  36445. /**
  36446. * A reference to a renderer module for managing shader program bindings.
  36447. *
  36448. * @private
  36449. * @type {?Bindings}
  36450. * @default null
  36451. */
  36452. this._bindings = null;
  36453. /**
  36454. * A reference to a renderer module for managing render objects.
  36455. *
  36456. * @private
  36457. * @type {?RenderObjects}
  36458. * @default null
  36459. */
  36460. this._objects = null;
  36461. /**
  36462. * A reference to a renderer module for managing render and compute pipelines.
  36463. *
  36464. * @private
  36465. * @type {?Pipelines}
  36466. * @default null
  36467. */
  36468. this._pipelines = null;
  36469. /**
  36470. * A reference to a renderer module for managing render bundles.
  36471. *
  36472. * @private
  36473. * @type {?RenderBundles}
  36474. * @default null
  36475. */
  36476. this._bundles = null;
  36477. /**
  36478. * A reference to a renderer module for managing render lists.
  36479. *
  36480. * @private
  36481. * @type {?RenderLists}
  36482. * @default null
  36483. */
  36484. this._renderLists = null;
  36485. /**
  36486. * A reference to a renderer module for managing render contexts.
  36487. *
  36488. * @private
  36489. * @type {?RenderContexts}
  36490. * @default null
  36491. */
  36492. this._renderContexts = null;
  36493. /**
  36494. * A reference to a renderer module for managing textures.
  36495. *
  36496. * @private
  36497. * @type {?Textures}
  36498. * @default null
  36499. */
  36500. this._textures = null;
  36501. /**
  36502. * A reference to a renderer module for backgrounds.
  36503. *
  36504. * @private
  36505. * @type {?Background}
  36506. * @default null
  36507. */
  36508. this._background = null;
  36509. /**
  36510. * This fullscreen quad is used for internal render passes
  36511. * like the tone mapping and color space output pass.
  36512. *
  36513. * @private
  36514. * @type {QuadMesh}
  36515. */
  36516. this._quad = new QuadMesh( new NodeMaterial() );
  36517. this._quad.material.name = 'Renderer_output';
  36518. /**
  36519. * A reference to the current render context.
  36520. *
  36521. * @private
  36522. * @type {?RenderContext}
  36523. * @default null
  36524. */
  36525. this._currentRenderContext = null;
  36526. /**
  36527. * A custom sort function for the opaque render list.
  36528. *
  36529. * @private
  36530. * @type {?Function}
  36531. * @default null
  36532. */
  36533. this._opaqueSort = null;
  36534. /**
  36535. * A custom sort function for the transparent render list.
  36536. *
  36537. * @private
  36538. * @type {?Function}
  36539. * @default null
  36540. */
  36541. this._transparentSort = null;
  36542. /**
  36543. * The framebuffer target.
  36544. *
  36545. * @private
  36546. * @type {?RenderTarget}
  36547. * @default null
  36548. */
  36549. this._frameBufferTarget = null;
  36550. const alphaClear = this.alpha === true ? 0 : 1;
  36551. /**
  36552. * The clear color value.
  36553. *
  36554. * @private
  36555. * @type {Color4}
  36556. */
  36557. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  36558. /**
  36559. * The clear depth value.
  36560. *
  36561. * @private
  36562. * @type {number}
  36563. * @default 1
  36564. */
  36565. this._clearDepth = 1;
  36566. /**
  36567. * The clear stencil value.
  36568. *
  36569. * @private
  36570. * @type {number}
  36571. * @default 0
  36572. */
  36573. this._clearStencil = 0;
  36574. /**
  36575. * The current render target.
  36576. *
  36577. * @private
  36578. * @type {?RenderTarget}
  36579. * @default null
  36580. */
  36581. this._renderTarget = null;
  36582. /**
  36583. * The active cube face.
  36584. *
  36585. * @private
  36586. * @type {number}
  36587. * @default 0
  36588. */
  36589. this._activeCubeFace = 0;
  36590. /**
  36591. * The active mipmap level.
  36592. *
  36593. * @private
  36594. * @type {number}
  36595. * @default 0
  36596. */
  36597. this._activeMipmapLevel = 0;
  36598. /**
  36599. * The current output render target.
  36600. *
  36601. * @private
  36602. * @type {?RenderTarget}
  36603. * @default null
  36604. */
  36605. this._outputRenderTarget = null;
  36606. /**
  36607. * The MRT setting.
  36608. *
  36609. * @private
  36610. * @type {?MRTNode}
  36611. * @default null
  36612. */
  36613. this._mrt = null;
  36614. /**
  36615. * This function defines how a render object is going
  36616. * to be rendered.
  36617. *
  36618. * @private
  36619. * @type {?Function}
  36620. * @default null
  36621. */
  36622. this._renderObjectFunction = null;
  36623. /**
  36624. * Used to keep track of the current render object function.
  36625. *
  36626. * @private
  36627. * @type {?Function}
  36628. * @default null
  36629. */
  36630. this._currentRenderObjectFunction = null;
  36631. /**
  36632. * Used to keep track of the current render bundle.
  36633. *
  36634. * @private
  36635. * @type {?RenderBundle}
  36636. * @default null
  36637. */
  36638. this._currentRenderBundle = null;
  36639. /**
  36640. * Next to `_renderObjectFunction()`, this function provides another hook
  36641. * for influencing the render process of a render object. It is meant for internal
  36642. * use and only relevant for `compileAsync()` right now. Instead of using
  36643. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  36644. * a different function might be used which performs no draw but just the node
  36645. * and pipeline updates.
  36646. *
  36647. * @private
  36648. * @type {?Function}
  36649. * @default null
  36650. */
  36651. this._handleObjectFunction = this._renderObjectDirect;
  36652. /**
  36653. * Indicates whether the device has been lost or not. In WebGL terms, the device
  36654. * lost is considered as a context lost. When this is set to `true`, rendering
  36655. * isn't possible anymore.
  36656. *
  36657. * @private
  36658. * @type {boolean}
  36659. * @default false
  36660. */
  36661. this._isDeviceLost = false;
  36662. /**
  36663. * A callback function that defines what should happen when a device/context lost occurs.
  36664. *
  36665. * @type {Function}
  36666. */
  36667. this.onDeviceLost = this._onDeviceLost;
  36668. /**
  36669. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  36670. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  36671. * This will reduce rendering quality though.
  36672. *
  36673. * @private
  36674. * @type {number}
  36675. * @default HalfFloatType
  36676. */
  36677. this._colorBufferType = colorBufferType;
  36678. /**
  36679. * Whether the renderer has been initialized or not.
  36680. *
  36681. * @private
  36682. * @type {boolean}
  36683. * @default false
  36684. */
  36685. this._initialized = false;
  36686. /**
  36687. * A reference to the promise which initializes the renderer.
  36688. *
  36689. * @private
  36690. * @type {?Promise<this>}
  36691. * @default null
  36692. */
  36693. this._initPromise = null;
  36694. /**
  36695. * An array of compilation promises which are used in `compileAsync()`.
  36696. *
  36697. * @private
  36698. * @type {?Array<Promise>}
  36699. * @default null
  36700. */
  36701. this._compilationPromises = null;
  36702. /**
  36703. * Whether the renderer should render transparent render objects or not.
  36704. *
  36705. * @type {boolean}
  36706. * @default true
  36707. */
  36708. this.transparent = true;
  36709. /**
  36710. * Whether the renderer should render opaque render objects or not.
  36711. *
  36712. * @type {boolean}
  36713. * @default true
  36714. */
  36715. this.opaque = true;
  36716. /**
  36717. * Shadow map configuration
  36718. * @typedef {Object} ShadowMapConfig
  36719. * @property {boolean} enabled - Whether to globally enable shadows or not.
  36720. * @property {number} type - The shadow map type.
  36721. */
  36722. /**
  36723. * The renderer's shadow configuration.
  36724. *
  36725. * @type {ShadowMapConfig}
  36726. */
  36727. this.shadowMap = {
  36728. enabled: false,
  36729. type: PCFShadowMap
  36730. };
  36731. /**
  36732. * XR configuration.
  36733. * @typedef {Object} XRConfig
  36734. * @property {boolean} enabled - Whether to globally enable XR or not.
  36735. */
  36736. /**
  36737. * The renderer's XR manager.
  36738. *
  36739. * @type {XRManager}
  36740. */
  36741. this.xr = new XRManager( this, multiview );
  36742. /**
  36743. * Debug configuration.
  36744. * @typedef {Object} DebugConfig
  36745. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  36746. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  36747. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  36748. */
  36749. /**
  36750. * The renderer's debug configuration.
  36751. *
  36752. * @type {DebugConfig}
  36753. */
  36754. this.debug = {
  36755. checkShaderErrors: true,
  36756. onShaderError: null,
  36757. getShaderAsync: async ( scene, camera, object ) => {
  36758. await this.compileAsync( scene, camera );
  36759. const renderList = this._renderLists.get( scene, camera );
  36760. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  36761. const material = scene.overrideMaterial || object.material;
  36762. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  36763. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  36764. return { fragmentShader, vertexShader };
  36765. }
  36766. };
  36767. }
  36768. /**
  36769. * Initializes the renderer so it is ready for usage.
  36770. *
  36771. * @async
  36772. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  36773. */
  36774. async init() {
  36775. if ( this._initialized ) {
  36776. throw new Error( 'Renderer: Backend has already been initialized.' );
  36777. }
  36778. if ( this._initPromise !== null ) {
  36779. return this._initPromise;
  36780. }
  36781. this._initPromise = new Promise( async ( resolve, reject ) => {
  36782. let backend = this.backend;
  36783. try {
  36784. await backend.init( this );
  36785. } catch ( error ) {
  36786. if ( this._getFallback !== null ) {
  36787. // try the fallback
  36788. try {
  36789. this.backend = backend = this._getFallback( error );
  36790. await backend.init( this );
  36791. } catch ( error ) {
  36792. reject( error );
  36793. return;
  36794. }
  36795. } else {
  36796. reject( error );
  36797. return;
  36798. }
  36799. }
  36800. this._nodes = new Nodes( this, backend );
  36801. this._animation = new Animation( this._nodes, this.info );
  36802. this._attributes = new Attributes( backend );
  36803. this._background = new Background( this, this._nodes );
  36804. this._geometries = new Geometries( this._attributes, this.info );
  36805. this._textures = new Textures( this, backend, this.info );
  36806. this._pipelines = new Pipelines( backend, this._nodes );
  36807. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  36808. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  36809. this._renderLists = new RenderLists( this.lighting );
  36810. this._bundles = new RenderBundles();
  36811. this._renderContexts = new RenderContexts();
  36812. //
  36813. this._animation.start();
  36814. this._initialized = true;
  36815. resolve( this );
  36816. } );
  36817. return this._initPromise;
  36818. }
  36819. /**
  36820. * The coordinate system of the renderer. The value of this property
  36821. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  36822. * `THREE.WebGPUCoordinateSystem`.
  36823. *
  36824. * @readonly
  36825. * @type {number}
  36826. */
  36827. get coordinateSystem() {
  36828. return this.backend.coordinateSystem;
  36829. }
  36830. /**
  36831. * Compiles all materials in the given scene. This can be useful to avoid a
  36832. * phenomenon which is called "shader compilation stutter", which occurs when
  36833. * rendering an object with a new shader for the first time.
  36834. *
  36835. * If you want to add a 3D object to an existing scene, use the third optional
  36836. * parameter for applying the target scene. Note that the (target) scene's lighting
  36837. * and environment must be configured before calling this method.
  36838. *
  36839. * @async
  36840. * @param {Object3D} scene - The scene or 3D object to precompile.
  36841. * @param {Camera} camera - The camera that is used to render the scene.
  36842. * @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.
  36843. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  36844. */
  36845. async compileAsync( scene, camera, targetScene = null ) {
  36846. if ( this._isDeviceLost === true ) return;
  36847. if ( this._initialized === false ) await this.init();
  36848. // preserve render tree
  36849. const nodeFrame = this._nodes.nodeFrame;
  36850. const previousRenderId = nodeFrame.renderId;
  36851. const previousRenderContext = this._currentRenderContext;
  36852. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  36853. const previousCompilationPromises = this._compilationPromises;
  36854. //
  36855. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  36856. if ( targetScene === null ) targetScene = scene;
  36857. const renderTarget = this._renderTarget;
  36858. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  36859. const activeMipmapLevel = this._activeMipmapLevel;
  36860. const compilationPromises = [];
  36861. this._currentRenderContext = renderContext;
  36862. this._currentRenderObjectFunction = this.renderObject;
  36863. this._handleObjectFunction = this._createObjectPipeline;
  36864. this._compilationPromises = compilationPromises;
  36865. nodeFrame.renderId ++;
  36866. //
  36867. nodeFrame.update();
  36868. //
  36869. renderContext.depth = this.depth;
  36870. renderContext.stencil = this.stencil;
  36871. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  36872. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  36873. //
  36874. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  36875. //
  36876. const renderList = this._renderLists.get( scene, camera );
  36877. renderList.begin();
  36878. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  36879. // include lights from target scene
  36880. if ( targetScene !== scene ) {
  36881. targetScene.traverseVisible( function ( object ) {
  36882. if ( object.isLight && object.layers.test( camera.layers ) ) {
  36883. renderList.pushLight( object );
  36884. }
  36885. } );
  36886. }
  36887. renderList.finish();
  36888. //
  36889. if ( renderTarget !== null ) {
  36890. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  36891. const renderTargetData = this._textures.get( renderTarget );
  36892. renderContext.textures = renderTargetData.textures;
  36893. renderContext.depthTexture = renderTargetData.depthTexture;
  36894. } else {
  36895. renderContext.textures = null;
  36896. renderContext.depthTexture = null;
  36897. }
  36898. //
  36899. this._background.update( sceneRef, renderList, renderContext );
  36900. // process render lists
  36901. const opaqueObjects = renderList.opaque;
  36902. const transparentObjects = renderList.transparent;
  36903. const transparentDoublePassObjects = renderList.transparentDoublePass;
  36904. const lightsNode = renderList.lightsNode;
  36905. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  36906. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  36907. // restore render tree
  36908. nodeFrame.renderId = previousRenderId;
  36909. this._currentRenderContext = previousRenderContext;
  36910. this._currentRenderObjectFunction = previousRenderObjectFunction;
  36911. this._compilationPromises = previousCompilationPromises;
  36912. this._handleObjectFunction = this._renderObjectDirect;
  36913. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  36914. await Promise.all( compilationPromises );
  36915. }
  36916. /**
  36917. * Renders the scene in an async fashion.
  36918. *
  36919. * @async
  36920. * @param {Object3D} scene - The scene or 3D object to render.
  36921. * @param {Camera} camera - The camera.
  36922. * @return {Promise} A Promise that resolves when the render has been finished.
  36923. */
  36924. async renderAsync( scene, camera ) {
  36925. if ( this._initialized === false ) await this.init();
  36926. this._renderScene( scene, camera );
  36927. }
  36928. /**
  36929. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  36930. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  36931. *
  36932. * @async
  36933. * @return {Promise} A Promise that resolves when synchronization has been finished.
  36934. */
  36935. async waitForGPU() {
  36936. await this.backend.waitForGPU();
  36937. }
  36938. /**
  36939. * Enables or disables high precision for model-view and normal-view matrices.
  36940. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  36941. *
  36942. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  36943. *
  36944. * @param {boolean} value - Whether to enable or disable high precision.
  36945. * @type {boolean}
  36946. */
  36947. set highPrecision( value ) {
  36948. if ( value === true ) {
  36949. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  36950. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  36951. } else if ( this.highPrecision ) {
  36952. this.overrideNodes.modelViewMatrix = null;
  36953. this.overrideNodes.modelNormalViewMatrix = null;
  36954. }
  36955. }
  36956. /**
  36957. * Returns whether high precision is enabled or not.
  36958. *
  36959. * @return {boolean} Whether high precision is enabled or not.
  36960. * @type {boolean}
  36961. */
  36962. get highPrecision() {
  36963. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  36964. }
  36965. /**
  36966. * Sets the given MRT configuration.
  36967. *
  36968. * @param {MRTNode} mrt - The MRT node to set.
  36969. * @return {Renderer} A reference to this renderer.
  36970. */
  36971. setMRT( mrt ) {
  36972. this._mrt = mrt;
  36973. return this;
  36974. }
  36975. /**
  36976. * Returns the MRT configuration.
  36977. *
  36978. * @return {MRTNode} The MRT configuration.
  36979. */
  36980. getMRT() {
  36981. return this._mrt;
  36982. }
  36983. /**
  36984. * Returns the color buffer type.
  36985. *
  36986. * @return {number} The color buffer type.
  36987. */
  36988. getColorBufferType() {
  36989. return this._colorBufferType;
  36990. }
  36991. /**
  36992. * Default implementation of the device lost callback.
  36993. *
  36994. * @private
  36995. * @param {Object} info - Information about the context lost.
  36996. */
  36997. _onDeviceLost( info ) {
  36998. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  36999. if ( info.reason ) {
  37000. errorMessage += `\nReason: ${info.reason}`;
  37001. }
  37002. console.error( errorMessage );
  37003. this._isDeviceLost = true;
  37004. }
  37005. /**
  37006. * Renders the given render bundle.
  37007. *
  37008. * @private
  37009. * @param {Object} bundle - Render bundle data.
  37010. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  37011. * @param {LightsNode} lightsNode - The lights node.
  37012. */
  37013. _renderBundle( bundle, sceneRef, lightsNode ) {
  37014. const { bundleGroup, camera, renderList } = bundle;
  37015. const renderContext = this._currentRenderContext;
  37016. //
  37017. const renderBundle = this._bundles.get( bundleGroup, camera );
  37018. const renderBundleData = this.backend.get( renderBundle );
  37019. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37020. //
  37021. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37022. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37023. renderBundleData.renderContexts.add( renderContext );
  37024. if ( renderBundleNeedsUpdate ) {
  37025. this.backend.beginBundle( renderContext );
  37026. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37027. renderBundleData.renderObjects = [];
  37028. }
  37029. this._currentRenderBundle = renderBundle;
  37030. const {
  37031. transparentDoublePass: transparentDoublePassObjects,
  37032. transparent: transparentObjects,
  37033. opaque: opaqueObjects
  37034. } = renderList;
  37035. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37036. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37037. this._currentRenderBundle = null;
  37038. //
  37039. this.backend.finishBundle( renderContext, renderBundle );
  37040. renderBundleData.version = bundleGroup.version;
  37041. } else {
  37042. const { renderObjects } = renderBundleData;
  37043. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37044. const renderObject = renderObjects[ i ];
  37045. if ( this._nodes.needsRefresh( renderObject ) ) {
  37046. this._nodes.updateBefore( renderObject );
  37047. this._nodes.updateForRender( renderObject );
  37048. this._bindings.updateForRender( renderObject );
  37049. this._nodes.updateAfter( renderObject );
  37050. }
  37051. }
  37052. }
  37053. this.backend.addBundle( renderContext, renderBundle );
  37054. }
  37055. /**
  37056. * Renders the scene or 3D object with the given camera. This method can only be called
  37057. * if the renderer has been initialized.
  37058. *
  37059. * The target of the method is the default framebuffer (meaning the canvas)
  37060. * or alternatively a render target when specified via `setRenderTarget()`.
  37061. *
  37062. * @param {Object3D} scene - The scene or 3D object to render.
  37063. * @param {Camera} camera - The camera to render the scene with.
  37064. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  37065. * Only returned when the renderer has not been initialized.
  37066. */
  37067. render( scene, camera ) {
  37068. if ( this._initialized === false ) {
  37069. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37070. return this.renderAsync( scene, camera );
  37071. }
  37072. this._renderScene( scene, camera );
  37073. }
  37074. /**
  37075. * Returns an internal render target which is used when computing the output tone mapping
  37076. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  37077. * pass and not inline to achieve more correct results.
  37078. *
  37079. * @private
  37080. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  37081. */
  37082. _getFrameBufferTarget() {
  37083. const { currentToneMapping, currentColorSpace } = this;
  37084. const useToneMapping = currentToneMapping !== NoToneMapping;
  37085. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37086. if ( useToneMapping === false && useColorSpace === false ) return null;
  37087. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  37088. const { depth, stencil } = this;
  37089. let frameBufferTarget = this._frameBufferTarget;
  37090. if ( frameBufferTarget === null ) {
  37091. frameBufferTarget = new RenderTarget( width, height, {
  37092. depthBuffer: depth,
  37093. stencilBuffer: stencil,
  37094. type: this._colorBufferType,
  37095. format: RGBAFormat,
  37096. colorSpace: LinearSRGBColorSpace,
  37097. generateMipmaps: false,
  37098. minFilter: LinearFilter,
  37099. magFilter: LinearFilter,
  37100. samples: this.samples
  37101. } );
  37102. frameBufferTarget.isPostProcessingRenderTarget = true;
  37103. this._frameBufferTarget = frameBufferTarget;
  37104. }
  37105. const outputRenderTarget = this.getOutputRenderTarget();
  37106. frameBufferTarget.depthBuffer = depth;
  37107. frameBufferTarget.stencilBuffer = stencil;
  37108. frameBufferTarget.setSize( width, height, outputRenderTarget !== null ? outputRenderTarget.depth : 1 );
  37109. frameBufferTarget.viewport.copy( this._viewport );
  37110. frameBufferTarget.scissor.copy( this._scissor );
  37111. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37112. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37113. frameBufferTarget.scissorTest = this._scissorTest;
  37114. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  37115. return frameBufferTarget;
  37116. }
  37117. /**
  37118. * Renders the scene or 3D object with the given camera.
  37119. *
  37120. * @private
  37121. * @param {Object3D} scene - The scene or 3D object to render.
  37122. * @param {Camera} camera - The camera to render the scene with.
  37123. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  37124. * @return {RenderContext} The current render context.
  37125. */
  37126. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37127. if ( this._isDeviceLost === true ) return;
  37128. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37129. // preserve render tree
  37130. const nodeFrame = this._nodes.nodeFrame;
  37131. const previousRenderId = nodeFrame.renderId;
  37132. const previousRenderContext = this._currentRenderContext;
  37133. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37134. //
  37135. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37136. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  37137. const activeCubeFace = this._activeCubeFace;
  37138. const activeMipmapLevel = this._activeMipmapLevel;
  37139. //
  37140. let renderTarget;
  37141. if ( frameBufferTarget !== null ) {
  37142. renderTarget = frameBufferTarget;
  37143. this.setRenderTarget( renderTarget );
  37144. } else {
  37145. renderTarget = outputRenderTarget;
  37146. }
  37147. //
  37148. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37149. this._currentRenderContext = renderContext;
  37150. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37151. //
  37152. this.info.calls ++;
  37153. this.info.render.calls ++;
  37154. this.info.render.frameCalls ++;
  37155. nodeFrame.renderId = this.info.calls;
  37156. //
  37157. const coordinateSystem = this.coordinateSystem;
  37158. const xr = this.xr;
  37159. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  37160. camera.coordinateSystem = coordinateSystem;
  37161. camera.updateProjectionMatrix();
  37162. if ( camera.isArrayCamera ) {
  37163. for ( const subCamera of camera.cameras ) {
  37164. subCamera.coordinateSystem = coordinateSystem;
  37165. subCamera.updateProjectionMatrix();
  37166. }
  37167. }
  37168. }
  37169. //
  37170. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37171. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37172. if ( xr.enabled === true && xr.isPresenting === true ) {
  37173. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  37174. camera = xr.getCamera(); // use XR camera for rendering
  37175. }
  37176. //
  37177. let viewport = this._viewport;
  37178. let scissor = this._scissor;
  37179. let pixelRatio = this._pixelRatio;
  37180. if ( renderTarget !== null ) {
  37181. viewport = renderTarget.viewport;
  37182. scissor = renderTarget.scissor;
  37183. pixelRatio = 1;
  37184. }
  37185. this.getDrawingBufferSize( _drawingBufferSize );
  37186. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  37187. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37188. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37189. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37190. renderContext.viewportValue.width >>= activeMipmapLevel;
  37191. renderContext.viewportValue.height >>= activeMipmapLevel;
  37192. renderContext.viewportValue.minDepth = minDepth;
  37193. renderContext.viewportValue.maxDepth = maxDepth;
  37194. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37195. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37196. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37197. renderContext.scissorValue.width >>= activeMipmapLevel;
  37198. renderContext.scissorValue.height >>= activeMipmapLevel;
  37199. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37200. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37201. //
  37202. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37203. //
  37204. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  37205. if ( ! camera.isArrayCamera ) {
  37206. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37207. frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37208. }
  37209. const renderList = this._renderLists.get( scene, camera );
  37210. renderList.begin();
  37211. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37212. renderList.finish();
  37213. if ( this.sortObjects === true ) {
  37214. renderList.sort( this._opaqueSort, this._transparentSort );
  37215. }
  37216. //
  37217. if ( renderTarget !== null ) {
  37218. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37219. const renderTargetData = this._textures.get( renderTarget );
  37220. renderContext.textures = renderTargetData.textures;
  37221. renderContext.depthTexture = renderTargetData.depthTexture;
  37222. renderContext.width = renderTargetData.width;
  37223. renderContext.height = renderTargetData.height;
  37224. renderContext.renderTarget = renderTarget;
  37225. renderContext.depth = renderTarget.depthBuffer;
  37226. renderContext.stencil = renderTarget.stencilBuffer;
  37227. } else {
  37228. renderContext.textures = null;
  37229. renderContext.depthTexture = null;
  37230. renderContext.width = this.domElement.width;
  37231. renderContext.height = this.domElement.height;
  37232. renderContext.depth = this.depth;
  37233. renderContext.stencil = this.stencil;
  37234. }
  37235. renderContext.width >>= activeMipmapLevel;
  37236. renderContext.height >>= activeMipmapLevel;
  37237. renderContext.activeCubeFace = activeCubeFace;
  37238. renderContext.activeMipmapLevel = activeMipmapLevel;
  37239. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37240. //
  37241. this._background.update( sceneRef, renderList, renderContext );
  37242. //
  37243. renderContext.camera = camera;
  37244. this.backend.beginRender( renderContext );
  37245. // process render lists
  37246. const {
  37247. bundles,
  37248. lightsNode,
  37249. transparentDoublePass: transparentDoublePassObjects,
  37250. transparent: transparentObjects,
  37251. opaque: opaqueObjects
  37252. } = renderList;
  37253. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37254. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37255. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37256. // finish render pass
  37257. this.backend.finishRender( renderContext );
  37258. // restore render tree
  37259. nodeFrame.renderId = previousRenderId;
  37260. this._currentRenderContext = previousRenderContext;
  37261. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37262. //
  37263. if ( frameBufferTarget !== null ) {
  37264. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37265. this._renderOutput( renderTarget );
  37266. }
  37267. //
  37268. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37269. //
  37270. return renderContext;
  37271. }
  37272. /**
  37273. * The output pass performs tone mapping and color space conversion.
  37274. *
  37275. * @private
  37276. * @param {RenderTarget} renderTarget - The current render target.
  37277. */
  37278. _renderOutput( renderTarget ) {
  37279. const quad = this._quad;
  37280. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37281. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37282. quad.material.needsUpdate = true;
  37283. }
  37284. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  37285. const currentAutoClear = this.autoClear;
  37286. const currentXR = this.xr.enabled;
  37287. this.autoClear = false;
  37288. this.xr.enabled = false;
  37289. this._renderScene( quad, quad.camera, false );
  37290. this.autoClear = currentAutoClear;
  37291. this.xr.enabled = currentXR;
  37292. }
  37293. /**
  37294. * Returns the maximum available anisotropy for texture filtering.
  37295. *
  37296. * @return {number} The maximum available anisotropy.
  37297. */
  37298. getMaxAnisotropy() {
  37299. return this.backend.getMaxAnisotropy();
  37300. }
  37301. /**
  37302. * Returns the active cube face.
  37303. *
  37304. * @return {number} The active cube face.
  37305. */
  37306. getActiveCubeFace() {
  37307. return this._activeCubeFace;
  37308. }
  37309. /**
  37310. * Returns the active mipmap level.
  37311. *
  37312. * @return {number} The active mipmap level.
  37313. */
  37314. getActiveMipmapLevel() {
  37315. return this._activeMipmapLevel;
  37316. }
  37317. /**
  37318. * Applications are advised to always define the animation loop
  37319. * with this method and not manually with `requestAnimationFrame()`
  37320. * for best compatibility.
  37321. *
  37322. * @async
  37323. * @param {?Function} callback - The application's animation loop.
  37324. * @return {Promise} A Promise that resolves when the set has been executed.
  37325. */
  37326. async setAnimationLoop( callback ) {
  37327. if ( this._initialized === false ) await this.init();
  37328. this._animation.setAnimationLoop( callback );
  37329. }
  37330. /**
  37331. * Can be used to transfer buffer data from a storage buffer attribute
  37332. * from the GPU to the CPU in context of compute shaders.
  37333. *
  37334. * @async
  37335. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37336. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37337. */
  37338. async getArrayBufferAsync( attribute ) {
  37339. return await this.backend.getArrayBufferAsync( attribute );
  37340. }
  37341. /**
  37342. * Returns the rendering context.
  37343. *
  37344. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  37345. */
  37346. getContext() {
  37347. return this.backend.getContext();
  37348. }
  37349. /**
  37350. * Returns the pixel ratio.
  37351. *
  37352. * @return {number} The pixel ratio.
  37353. */
  37354. getPixelRatio() {
  37355. return this._pixelRatio;
  37356. }
  37357. /**
  37358. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  37359. *
  37360. * @param {Vector2} target - The method writes the result in this target object.
  37361. * @return {Vector2} The drawing buffer size.
  37362. */
  37363. getDrawingBufferSize( target ) {
  37364. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37365. }
  37366. /**
  37367. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  37368. *
  37369. * @param {Vector2} target - The method writes the result in this target object.
  37370. * @return {Vector2} The renderer's size in logical pixels.
  37371. */
  37372. getSize( target ) {
  37373. return target.set( this._width, this._height );
  37374. }
  37375. /**
  37376. * Sets the given pixel ratio and resizes the canvas if necessary.
  37377. *
  37378. * @param {number} [value=1] - The pixel ratio.
  37379. */
  37380. setPixelRatio( value = 1 ) {
  37381. if ( this._pixelRatio === value ) return;
  37382. this._pixelRatio = value;
  37383. this.setSize( this._width, this._height, false );
  37384. }
  37385. /**
  37386. * This method allows to define the drawing buffer size by specifying
  37387. * width, height and pixel ratio all at once. The size of the drawing
  37388. * buffer is computed with this formula:
  37389. * ```js
  37390. * size.x = width * pixelRatio;
  37391. * size.y = height * pixelRatio;
  37392. * ```
  37393. *
  37394. * @param {number} width - The width in logical pixels.
  37395. * @param {number} height - The height in logical pixels.
  37396. * @param {number} pixelRatio - The pixel ratio.
  37397. */
  37398. setDrawingBufferSize( width, height, pixelRatio ) {
  37399. // Renderer can't be resized while presenting in XR.
  37400. if ( this.xr && this.xr.isPresenting ) return;
  37401. this._width = width;
  37402. this._height = height;
  37403. this._pixelRatio = pixelRatio;
  37404. this.domElement.width = Math.floor( width * pixelRatio );
  37405. this.domElement.height = Math.floor( height * pixelRatio );
  37406. this.setViewport( 0, 0, width, height );
  37407. if ( this._initialized ) this.backend.updateSize();
  37408. }
  37409. /**
  37410. * Sets the size of the renderer.
  37411. *
  37412. * @param {number} width - The width in logical pixels.
  37413. * @param {number} height - The height in logical pixels.
  37414. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  37415. */
  37416. setSize( width, height, updateStyle = true ) {
  37417. // Renderer can't be resized while presenting in XR.
  37418. if ( this.xr && this.xr.isPresenting ) return;
  37419. this._width = width;
  37420. this._height = height;
  37421. this.domElement.width = Math.floor( width * this._pixelRatio );
  37422. this.domElement.height = Math.floor( height * this._pixelRatio );
  37423. if ( updateStyle === true ) {
  37424. this.domElement.style.width = width + 'px';
  37425. this.domElement.style.height = height + 'px';
  37426. }
  37427. this.setViewport( 0, 0, width, height );
  37428. if ( this._initialized ) this.backend.updateSize();
  37429. }
  37430. /**
  37431. * Defines a manual sort function for the opaque render list.
  37432. * Pass `null` to use the default sort.
  37433. *
  37434. * @param {Function} method - The sort function.
  37435. */
  37436. setOpaqueSort( method ) {
  37437. this._opaqueSort = method;
  37438. }
  37439. /**
  37440. * Defines a manual sort function for the transparent render list.
  37441. * Pass `null` to use the default sort.
  37442. *
  37443. * @param {Function} method - The sort function.
  37444. */
  37445. setTransparentSort( method ) {
  37446. this._transparentSort = method;
  37447. }
  37448. /**
  37449. * Returns the scissor rectangle.
  37450. *
  37451. * @param {Vector4} target - The method writes the result in this target object.
  37452. * @return {Vector4} The scissor rectangle.
  37453. */
  37454. getScissor( target ) {
  37455. const scissor = this._scissor;
  37456. target.x = scissor.x;
  37457. target.y = scissor.y;
  37458. target.width = scissor.width;
  37459. target.height = scissor.height;
  37460. return target;
  37461. }
  37462. /**
  37463. * Defines the scissor rectangle.
  37464. *
  37465. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  37466. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  37467. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  37468. * @param {number} width - The width of the scissor box in logical pixel unit.
  37469. * @param {number} height - The height of the scissor box in logical pixel unit.
  37470. */
  37471. setScissor( x, y, width, height ) {
  37472. const scissor = this._scissor;
  37473. if ( x.isVector4 ) {
  37474. scissor.copy( x );
  37475. } else {
  37476. scissor.set( x, y, width, height );
  37477. }
  37478. }
  37479. /**
  37480. * Returns the scissor test value.
  37481. *
  37482. * @return {boolean} Whether the scissor test should be enabled or not.
  37483. */
  37484. getScissorTest() {
  37485. return this._scissorTest;
  37486. }
  37487. /**
  37488. * Defines the scissor test.
  37489. *
  37490. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  37491. */
  37492. setScissorTest( boolean ) {
  37493. this._scissorTest = boolean;
  37494. this.backend.setScissorTest( boolean );
  37495. }
  37496. /**
  37497. * Returns the viewport definition.
  37498. *
  37499. * @param {Vector4} target - The method writes the result in this target object.
  37500. * @return {Vector4} The viewport definition.
  37501. */
  37502. getViewport( target ) {
  37503. return target.copy( this._viewport );
  37504. }
  37505. /**
  37506. * Defines the viewport.
  37507. *
  37508. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  37509. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  37510. * @param {number} width - The width of the viewport in logical pixel unit.
  37511. * @param {number} height - The height of the viewport in logical pixel unit.
  37512. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  37513. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  37514. */
  37515. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  37516. const viewport = this._viewport;
  37517. if ( x.isVector4 ) {
  37518. viewport.copy( x );
  37519. } else {
  37520. viewport.set( x, y, width, height );
  37521. }
  37522. viewport.minDepth = minDepth;
  37523. viewport.maxDepth = maxDepth;
  37524. }
  37525. /**
  37526. * Returns the clear color.
  37527. *
  37528. * @param {Color} target - The method writes the result in this target object.
  37529. * @return {Color} The clear color.
  37530. */
  37531. getClearColor( target ) {
  37532. return target.copy( this._clearColor );
  37533. }
  37534. /**
  37535. * Defines the clear color and optionally the clear alpha.
  37536. *
  37537. * @param {Color} color - The clear color.
  37538. * @param {number} [alpha=1] - The clear alpha.
  37539. */
  37540. setClearColor( color, alpha = 1 ) {
  37541. this._clearColor.set( color );
  37542. this._clearColor.a = alpha;
  37543. }
  37544. /**
  37545. * Returns the clear alpha.
  37546. *
  37547. * @return {number} The clear alpha.
  37548. */
  37549. getClearAlpha() {
  37550. return this._clearColor.a;
  37551. }
  37552. /**
  37553. * Defines the clear alpha.
  37554. *
  37555. * @param {number} alpha - The clear alpha.
  37556. */
  37557. setClearAlpha( alpha ) {
  37558. this._clearColor.a = alpha;
  37559. }
  37560. /**
  37561. * Returns the clear depth.
  37562. *
  37563. * @return {number} The clear depth.
  37564. */
  37565. getClearDepth() {
  37566. return this._clearDepth;
  37567. }
  37568. /**
  37569. * Defines the clear depth.
  37570. *
  37571. * @param {number} depth - The clear depth.
  37572. */
  37573. setClearDepth( depth ) {
  37574. this._clearDepth = depth;
  37575. }
  37576. /**
  37577. * Returns the clear stencil.
  37578. *
  37579. * @return {number} The clear stencil.
  37580. */
  37581. getClearStencil() {
  37582. return this._clearStencil;
  37583. }
  37584. /**
  37585. * Defines the clear stencil.
  37586. *
  37587. * @param {number} stencil - The clear stencil.
  37588. */
  37589. setClearStencil( stencil ) {
  37590. this._clearStencil = stencil;
  37591. }
  37592. /**
  37593. * This method performs an occlusion query for the given 3D object.
  37594. * It returns `true` if the given 3D object is fully occluded by other
  37595. * 3D objects in the scene.
  37596. *
  37597. * @param {Object3D} object - The 3D object to test.
  37598. * @return {boolean} Whether the 3D object is fully occluded or not.
  37599. */
  37600. isOccluded( object ) {
  37601. const renderContext = this._currentRenderContext;
  37602. return renderContext && this.backend.isOccluded( renderContext, object );
  37603. }
  37604. /**
  37605. * Performs a manual clear operation. This method ignores `autoClear` properties.
  37606. *
  37607. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  37608. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  37609. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  37610. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37611. * Only returned when the renderer has not been initialized.
  37612. */
  37613. clear( color = true, depth = true, stencil = true ) {
  37614. if ( this._initialized === false ) {
  37615. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  37616. return this.clearAsync( color, depth, stencil );
  37617. }
  37618. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37619. let renderContext = null;
  37620. if ( renderTarget !== null ) {
  37621. this._textures.updateRenderTarget( renderTarget );
  37622. const renderTargetData = this._textures.get( renderTarget );
  37623. renderContext = this._renderContexts.getForClear( renderTarget );
  37624. renderContext.textures = renderTargetData.textures;
  37625. renderContext.depthTexture = renderTargetData.depthTexture;
  37626. renderContext.width = renderTargetData.width;
  37627. renderContext.height = renderTargetData.height;
  37628. renderContext.renderTarget = renderTarget;
  37629. renderContext.depth = renderTarget.depthBuffer;
  37630. renderContext.stencil = renderTarget.stencilBuffer;
  37631. // #30329
  37632. renderContext.clearColorValue = this.backend.getClearColor();
  37633. renderContext.activeCubeFace = this.getActiveCubeFace();
  37634. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  37635. }
  37636. this.backend.clear( color, depth, stencil, renderContext );
  37637. if ( renderTarget !== null && this._renderTarget === null ) {
  37638. this._renderOutput( renderTarget );
  37639. }
  37640. }
  37641. /**
  37642. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  37643. *
  37644. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37645. * Only returned when the renderer has not been initialized.
  37646. */
  37647. clearColor() {
  37648. return this.clear( true, false, false );
  37649. }
  37650. /**
  37651. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  37652. *
  37653. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37654. * Only returned when the renderer has not been initialized.
  37655. */
  37656. clearDepth() {
  37657. return this.clear( false, true, false );
  37658. }
  37659. /**
  37660. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  37661. *
  37662. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37663. * Only returned when the renderer has not been initialized.
  37664. */
  37665. clearStencil() {
  37666. return this.clear( false, false, true );
  37667. }
  37668. /**
  37669. * Async version of {@link Renderer#clear}.
  37670. *
  37671. * @async
  37672. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  37673. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  37674. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  37675. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37676. */
  37677. async clearAsync( color = true, depth = true, stencil = true ) {
  37678. if ( this._initialized === false ) await this.init();
  37679. this.clear( color, depth, stencil );
  37680. }
  37681. /**
  37682. * Async version of {@link Renderer#clearColor}.
  37683. *
  37684. * @async
  37685. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37686. */
  37687. async clearColorAsync() {
  37688. this.clearAsync( true, false, false );
  37689. }
  37690. /**
  37691. * Async version of {@link Renderer#clearDepth}.
  37692. *
  37693. * @async
  37694. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37695. */
  37696. async clearDepthAsync() {
  37697. this.clearAsync( false, true, false );
  37698. }
  37699. /**
  37700. * Async version of {@link Renderer#clearStencil}.
  37701. *
  37702. * @async
  37703. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  37704. */
  37705. async clearStencilAsync() {
  37706. this.clearAsync( false, false, true );
  37707. }
  37708. /**
  37709. * The current output tone mapping of the renderer. When a render target is set,
  37710. * the output tone mapping is always `NoToneMapping`.
  37711. *
  37712. * @type {number}
  37713. */
  37714. get currentToneMapping() {
  37715. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  37716. }
  37717. /**
  37718. * The current output color space of the renderer. When a render target is set,
  37719. * the output color space is always `LinearSRGBColorSpace`.
  37720. *
  37721. * @type {string}
  37722. */
  37723. get currentColorSpace() {
  37724. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  37725. }
  37726. /**
  37727. * Returns `true` if the rendering settings are set to screen output.
  37728. *
  37729. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  37730. */
  37731. get isOutputTarget() {
  37732. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  37733. }
  37734. /**
  37735. * Frees all internal resources of the renderer. Call this method if the renderer
  37736. * is no longer in use by your app.
  37737. */
  37738. dispose() {
  37739. this.info.dispose();
  37740. this.backend.dispose();
  37741. this._animation.dispose();
  37742. this._objects.dispose();
  37743. this._pipelines.dispose();
  37744. this._nodes.dispose();
  37745. this._bindings.dispose();
  37746. this._renderLists.dispose();
  37747. this._renderContexts.dispose();
  37748. this._textures.dispose();
  37749. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  37750. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  37751. if ( queryPool !== null ) queryPool.dispose();
  37752. } );
  37753. this.setRenderTarget( null );
  37754. this.setAnimationLoop( null );
  37755. }
  37756. /**
  37757. * Sets the given render target. Calling this method means the renderer does not
  37758. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  37759. * Use `null` as the first argument to reset the state.
  37760. *
  37761. * @param {?RenderTarget} renderTarget - The render target to set.
  37762. * @param {number} [activeCubeFace=0] - The active cube face.
  37763. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  37764. */
  37765. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  37766. this._renderTarget = renderTarget;
  37767. this._activeCubeFace = activeCubeFace;
  37768. this._activeMipmapLevel = activeMipmapLevel;
  37769. }
  37770. /**
  37771. * Returns the current render target.
  37772. *
  37773. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  37774. */
  37775. getRenderTarget() {
  37776. return this._renderTarget;
  37777. }
  37778. /**
  37779. * Sets the output render target for the renderer.
  37780. *
  37781. * @param {Object} renderTarget - The render target to set as the output target.
  37782. */
  37783. setOutputRenderTarget( renderTarget ) {
  37784. this._outputRenderTarget = renderTarget;
  37785. }
  37786. /**
  37787. * Returns the current output target.
  37788. *
  37789. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  37790. */
  37791. getOutputRenderTarget() {
  37792. return this._outputRenderTarget;
  37793. }
  37794. /**
  37795. * Callback for {@link Renderer#setRenderObjectFunction}.
  37796. *
  37797. * @callback renderObjectFunction
  37798. * @param {Object3D} object - The 3D object.
  37799. * @param {Scene} scene - The scene the 3D object belongs to.
  37800. * @param {Camera} camera - The camera the object should be rendered with.
  37801. * @param {BufferGeometry} geometry - The object's geometry.
  37802. * @param {Material} material - The object's material.
  37803. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  37804. * @param {LightsNode} lightsNode - The current lights node.
  37805. * @param {ClippingContext} clippingContext - The clipping context.
  37806. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  37807. */
  37808. /**
  37809. * Sets the given render object function. Calling this method overwrites the default implementation
  37810. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  37811. * if you want to modify the way objects are rendered. For example you can define things like "every
  37812. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  37813. * The custom function must always call `renderObject()` in its implementation.
  37814. *
  37815. * Use `null` as the first argument to reset the state.
  37816. *
  37817. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  37818. */
  37819. setRenderObjectFunction( renderObjectFunction ) {
  37820. this._renderObjectFunction = renderObjectFunction;
  37821. }
  37822. /**
  37823. * Returns the current render object function.
  37824. *
  37825. * @return {?Function} The current render object function. Returns `null` if no function is set.
  37826. */
  37827. getRenderObjectFunction() {
  37828. return this._renderObjectFunction;
  37829. }
  37830. /**
  37831. * Execute a single or an array of compute nodes. This method can only be called
  37832. * if the renderer has been initialized.
  37833. *
  37834. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  37835. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  37836. */
  37837. compute( computeNodes ) {
  37838. if ( this._isDeviceLost === true ) return;
  37839. if ( this._initialized === false ) {
  37840. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  37841. return this.computeAsync( computeNodes );
  37842. }
  37843. //
  37844. const nodeFrame = this._nodes.nodeFrame;
  37845. const previousRenderId = nodeFrame.renderId;
  37846. //
  37847. this.info.calls ++;
  37848. this.info.compute.calls ++;
  37849. this.info.compute.frameCalls ++;
  37850. nodeFrame.renderId = this.info.calls;
  37851. //
  37852. const backend = this.backend;
  37853. const pipelines = this._pipelines;
  37854. const bindings = this._bindings;
  37855. const nodes = this._nodes;
  37856. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  37857. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  37858. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  37859. }
  37860. backend.beginCompute( computeNodes );
  37861. for ( const computeNode of computeList ) {
  37862. // onInit
  37863. if ( pipelines.has( computeNode ) === false ) {
  37864. const dispose = () => {
  37865. computeNode.removeEventListener( 'dispose', dispose );
  37866. pipelines.delete( computeNode );
  37867. bindings.delete( computeNode );
  37868. nodes.delete( computeNode );
  37869. };
  37870. computeNode.addEventListener( 'dispose', dispose );
  37871. //
  37872. const onInitFn = computeNode.onInitFunction;
  37873. if ( onInitFn !== null ) {
  37874. onInitFn.call( computeNode, { renderer: this } );
  37875. }
  37876. }
  37877. nodes.updateForCompute( computeNode );
  37878. bindings.updateForCompute( computeNode );
  37879. const computeBindings = bindings.getForCompute( computeNode );
  37880. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  37881. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  37882. }
  37883. backend.finishCompute( computeNodes );
  37884. //
  37885. nodeFrame.renderId = previousRenderId;
  37886. }
  37887. /**
  37888. * Execute a single or an array of compute nodes.
  37889. *
  37890. * @async
  37891. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  37892. * @return {Promise} A Promise that resolve when the compute has finished.
  37893. */
  37894. async computeAsync( computeNodes ) {
  37895. if ( this._initialized === false ) await this.init();
  37896. this.compute( computeNodes );
  37897. }
  37898. /**
  37899. * Checks if the given feature is supported by the selected backend.
  37900. *
  37901. * @async
  37902. * @param {string} name - The feature's name.
  37903. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  37904. */
  37905. async hasFeatureAsync( name ) {
  37906. if ( this._initialized === false ) await this.init();
  37907. return this.backend.hasFeature( name );
  37908. }
  37909. async resolveTimestampsAsync( type = 'render' ) {
  37910. if ( this._initialized === false ) await this.init();
  37911. return this.backend.resolveTimestampsAsync( type );
  37912. }
  37913. /**
  37914. * Checks if the given feature is supported by the selected backend. If the
  37915. * renderer has not been initialized, this method always returns `false`.
  37916. *
  37917. * @param {string} name - The feature's name.
  37918. * @return {boolean} Whether the feature is supported or not.
  37919. */
  37920. hasFeature( name ) {
  37921. if ( this._initialized === false ) {
  37922. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  37923. return false;
  37924. }
  37925. return this.backend.hasFeature( name );
  37926. }
  37927. /**
  37928. * Returns `true` when the renderer has been initialized.
  37929. *
  37930. * @return {boolean} Whether the renderer has been initialized or not.
  37931. */
  37932. hasInitialized() {
  37933. return this._initialized;
  37934. }
  37935. /**
  37936. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  37937. * (which can cause noticeable lags due to decode and GPU upload overhead).
  37938. *
  37939. * @async
  37940. * @param {Texture} texture - The texture.
  37941. * @return {Promise} A Promise that resolves when the texture has been initialized.
  37942. */
  37943. async initTextureAsync( texture ) {
  37944. if ( this._initialized === false ) await this.init();
  37945. this._textures.updateTexture( texture );
  37946. }
  37947. /**
  37948. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  37949. * (which can cause noticeable lags due to decode and GPU upload overhead).
  37950. *
  37951. * This method can only be used if the renderer has been initialized.
  37952. *
  37953. * @param {Texture} texture - The texture.
  37954. */
  37955. initTexture( texture ) {
  37956. if ( this._initialized === false ) {
  37957. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  37958. }
  37959. this._textures.updateTexture( texture );
  37960. }
  37961. /**
  37962. * Copies the current bound framebuffer into the given texture.
  37963. *
  37964. * @param {FramebufferTexture} framebufferTexture - The texture.
  37965. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  37966. */
  37967. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  37968. if ( rectangle !== null ) {
  37969. if ( rectangle.isVector2 ) {
  37970. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  37971. } else if ( rectangle.isVector4 ) {
  37972. rectangle = _vector4.copy( rectangle ).floor();
  37973. } else {
  37974. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  37975. return;
  37976. }
  37977. } else {
  37978. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  37979. }
  37980. //
  37981. let renderContext = this._currentRenderContext;
  37982. let renderTarget;
  37983. if ( renderContext !== null ) {
  37984. renderTarget = renderContext.renderTarget;
  37985. } else {
  37986. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  37987. if ( renderTarget !== null ) {
  37988. this._textures.updateRenderTarget( renderTarget );
  37989. renderContext = this._textures.get( renderTarget );
  37990. }
  37991. }
  37992. //
  37993. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  37994. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  37995. }
  37996. /**
  37997. * Copies data of the given source texture into a destination texture.
  37998. *
  37999. * @param {Texture} srcTexture - The source texture.
  38000. * @param {Texture} dstTexture - The destination texture.
  38001. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  38002. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  38003. * @param {number} [srcLevel=0] - The source mip level to copy from.
  38004. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  38005. */
  38006. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  38007. this._textures.updateTexture( srcTexture );
  38008. this._textures.updateTexture( dstTexture );
  38009. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  38010. }
  38011. /**
  38012. * Reads pixel data from the given render target.
  38013. *
  38014. * @async
  38015. * @param {RenderTarget} renderTarget - The render target to read from.
  38016. * @param {number} x - The `x` coordinate of the copy region's origin.
  38017. * @param {number} y - The `y` coordinate of the copy region's origin.
  38018. * @param {number} width - The width of the copy region.
  38019. * @param {number} height - The height of the copy region.
  38020. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  38021. * @param {number} [faceIndex=0] - The active cube face index.
  38022. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  38023. */
  38024. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  38025. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  38026. }
  38027. /**
  38028. * Analyzes the given 3D object's hierarchy and builds render lists from the
  38029. * processed hierarchy.
  38030. *
  38031. * @param {Object3D} object - The 3D object to process (usually a scene).
  38032. * @param {Camera} camera - The camera the object is rendered with.
  38033. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  38034. * @param {RenderList} renderList - The current render list.
  38035. * @param {ClippingContext} clippingContext - The current clipping context.
  38036. */
  38037. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  38038. if ( object.visible === false ) return;
  38039. const visible = object.layers.test( camera.layers );
  38040. if ( visible ) {
  38041. if ( object.isGroup ) {
  38042. groupOrder = object.renderOrder;
  38043. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  38044. } else if ( object.isLOD ) {
  38045. if ( object.autoUpdate === true ) object.update( camera );
  38046. } else if ( object.isLight ) {
  38047. renderList.pushLight( object );
  38048. } else if ( object.isSprite ) {
  38049. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38050. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  38051. if ( this.sortObjects === true ) {
  38052. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38053. }
  38054. const { geometry, material } = object;
  38055. if ( material.visible ) {
  38056. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38057. }
  38058. }
  38059. } else if ( object.isLineLoop ) {
  38060. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38061. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38062. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38063. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  38064. const { geometry, material } = object;
  38065. if ( this.sortObjects === true ) {
  38066. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38067. _vector4
  38068. .copy( geometry.boundingSphere.center )
  38069. .applyMatrix4( object.matrixWorld )
  38070. .applyMatrix4( _projScreenMatrix );
  38071. }
  38072. if ( Array.isArray( material ) ) {
  38073. const groups = geometry.groups;
  38074. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38075. const group = groups[ i ];
  38076. const groupMaterial = material[ group.materialIndex ];
  38077. if ( groupMaterial && groupMaterial.visible ) {
  38078. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  38079. }
  38080. }
  38081. } else if ( material.visible ) {
  38082. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38083. }
  38084. }
  38085. }
  38086. }
  38087. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38088. const baseRenderList = renderList;
  38089. // replace render list
  38090. renderList = this._renderLists.get( object, camera );
  38091. renderList.begin();
  38092. baseRenderList.pushBundle( {
  38093. bundleGroup: object,
  38094. camera,
  38095. renderList,
  38096. } );
  38097. renderList.finish();
  38098. }
  38099. const children = object.children;
  38100. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38101. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  38102. }
  38103. }
  38104. /**
  38105. * Renders the given render bundles.
  38106. *
  38107. * @private
  38108. * @param {Array<Object>} bundles - Array with render bundle data.
  38109. * @param {Scene} sceneRef - The scene the render bundles belong to.
  38110. * @param {LightsNode} lightsNode - The current lights node.
  38111. */
  38112. _renderBundles( bundles, sceneRef, lightsNode ) {
  38113. for ( const bundle of bundles ) {
  38114. this._renderBundle( bundle, sceneRef, lightsNode );
  38115. }
  38116. }
  38117. /**
  38118. * Renders the transparent objects from the given render lists.
  38119. *
  38120. * @private
  38121. * @param {Array<Object>} renderList - The transparent render list.
  38122. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  38123. * @param {Camera} camera - The camera the render list should be rendered with.
  38124. * @param {Scene} scene - The scene the render list belongs to.
  38125. * @param {LightsNode} lightsNode - The current lights node.
  38126. */
  38127. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  38128. if ( doublePassList.length > 0 ) {
  38129. // render back side
  38130. for ( const { material } of doublePassList ) {
  38131. material.side = BackSide;
  38132. }
  38133. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  38134. // render front side
  38135. for ( const { material } of doublePassList ) {
  38136. material.side = FrontSide;
  38137. }
  38138. this._renderObjects( renderList, camera, scene, lightsNode );
  38139. // restore
  38140. for ( const { material } of doublePassList ) {
  38141. material.side = DoubleSide;
  38142. }
  38143. } else {
  38144. this._renderObjects( renderList, camera, scene, lightsNode );
  38145. }
  38146. }
  38147. /**
  38148. * Renders the objects from the given render list.
  38149. *
  38150. * @private
  38151. * @param {Array<Object>} renderList - The render list.
  38152. * @param {Camera} camera - The camera the render list should be rendered with.
  38153. * @param {Scene} scene - The scene the render list belongs to.
  38154. * @param {LightsNode} lightsNode - The current lights node.
  38155. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38156. */
  38157. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  38158. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38159. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  38160. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  38161. }
  38162. }
  38163. /**
  38164. * This method represents the default render object function that manages the render lifecycle
  38165. * of the object.
  38166. *
  38167. * @param {Object3D} object - The 3D object.
  38168. * @param {Scene} scene - The scene the 3D object belongs to.
  38169. * @param {Camera} camera - The camera the object should be rendered with.
  38170. * @param {BufferGeometry} geometry - The object's geometry.
  38171. * @param {Material} material - The object's material.
  38172. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38173. * @param {LightsNode} lightsNode - The current lights node.
  38174. * @param {?ClippingContext} clippingContext - The clipping context.
  38175. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38176. */
  38177. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  38178. let overridePositionNode;
  38179. let overrideColorNode;
  38180. let overrideDepthNode;
  38181. //
  38182. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38183. //
  38184. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  38185. const overrideMaterial = scene.overrideMaterial;
  38186. if ( material.positionNode && material.positionNode.isNode ) {
  38187. overridePositionNode = overrideMaterial.positionNode;
  38188. overrideMaterial.positionNode = material.positionNode;
  38189. }
  38190. overrideMaterial.alphaTest = material.alphaTest;
  38191. overrideMaterial.alphaMap = material.alphaMap;
  38192. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  38193. if ( overrideMaterial.isShadowPassMaterial ) {
  38194. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38195. if ( material.depthNode && material.depthNode.isNode ) {
  38196. overrideDepthNode = overrideMaterial.depthNode;
  38197. overrideMaterial.depthNode = material.depthNode;
  38198. }
  38199. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  38200. overrideColorNode = overrideMaterial.colorNode;
  38201. overrideMaterial.colorNode = material.castShadowNode;
  38202. }
  38203. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  38204. overridePositionNode = overrideMaterial.positionNode;
  38205. overrideMaterial.positionNode = material.castShadowPositionNode;
  38206. }
  38207. }
  38208. material = overrideMaterial;
  38209. }
  38210. //
  38211. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38212. material.side = BackSide;
  38213. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  38214. material.side = FrontSide;
  38215. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  38216. material.side = DoubleSide;
  38217. } else {
  38218. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  38219. }
  38220. //
  38221. if ( overridePositionNode !== undefined ) {
  38222. scene.overrideMaterial.positionNode = overridePositionNode;
  38223. }
  38224. if ( overrideDepthNode !== undefined ) {
  38225. scene.overrideMaterial.depthNode = overrideDepthNode;
  38226. }
  38227. if ( overrideColorNode !== undefined ) {
  38228. scene.overrideMaterial.colorNode = overrideColorNode;
  38229. }
  38230. //
  38231. object.onAfterRender( this, scene, camera, geometry, material, group );
  38232. }
  38233. /**
  38234. * This method represents the default `_handleObjectFunction` implementation which creates
  38235. * a render object from the given data and performs the draw command with the selected backend.
  38236. *
  38237. * @private
  38238. * @param {Object3D} object - The 3D object.
  38239. * @param {Material} material - The object's material.
  38240. * @param {Scene} scene - The scene the 3D object belongs to.
  38241. * @param {Camera} camera - The camera the object should be rendered with.
  38242. * @param {LightsNode} lightsNode - The current lights node.
  38243. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38244. * @param {ClippingContext} clippingContext - The clipping context.
  38245. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38246. */
  38247. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38248. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38249. renderObject.drawRange = object.geometry.drawRange;
  38250. renderObject.group = group;
  38251. //
  38252. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38253. if ( needsRefresh ) {
  38254. this._nodes.updateBefore( renderObject );
  38255. this._geometries.updateForRender( renderObject );
  38256. this._nodes.updateForRender( renderObject );
  38257. this._bindings.updateForRender( renderObject );
  38258. }
  38259. this._pipelines.updateForRender( renderObject );
  38260. //
  38261. if ( this._currentRenderBundle !== null ) {
  38262. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38263. renderBundleData.renderObjects.push( renderObject );
  38264. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  38265. }
  38266. this.backend.draw( renderObject, this.info );
  38267. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38268. }
  38269. /**
  38270. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  38271. * Used in `compileAsync()`.
  38272. *
  38273. * @private
  38274. * @param {Object3D} object - The 3D object.
  38275. * @param {Material} material - The object's material.
  38276. * @param {Scene} scene - The scene the 3D object belongs to.
  38277. * @param {Camera} camera - The camera the object should be rendered with.
  38278. * @param {LightsNode} lightsNode - The current lights node.
  38279. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38280. * @param {ClippingContext} clippingContext - The clipping context.
  38281. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38282. */
  38283. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38284. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38285. renderObject.drawRange = object.geometry.drawRange;
  38286. renderObject.group = group;
  38287. //
  38288. this._nodes.updateBefore( renderObject );
  38289. this._geometries.updateForRender( renderObject );
  38290. this._nodes.updateForRender( renderObject );
  38291. this._bindings.updateForRender( renderObject );
  38292. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38293. this._nodes.updateAfter( renderObject );
  38294. }
  38295. /**
  38296. * Alias for `compileAsync()`.
  38297. *
  38298. * @method
  38299. * @param {Object3D} scene - The scene or 3D object to precompile.
  38300. * @param {Camera} camera - The camera that is used to render the scene.
  38301. * @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.
  38302. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  38303. */
  38304. get compile() {
  38305. return this.compileAsync;
  38306. }
  38307. }
  38308. /**
  38309. * A binding represents the connection between a resource (like a texture, sampler
  38310. * or uniform buffer) and the resource definition in a shader stage.
  38311. *
  38312. * This module is an abstract base class for all concrete bindings types.
  38313. *
  38314. * @abstract
  38315. * @private
  38316. */
  38317. class Binding {
  38318. /**
  38319. * Constructs a new binding.
  38320. *
  38321. * @param {string} [name=''] - The binding's name.
  38322. */
  38323. constructor( name = '' ) {
  38324. /**
  38325. * The binding's name.
  38326. *
  38327. * @type {string}
  38328. */
  38329. this.name = name;
  38330. /**
  38331. * A bitmask that defines in what shader stages the
  38332. * binding's resource is accessible.
  38333. *
  38334. * @type {number}
  38335. */
  38336. this.visibility = 0;
  38337. }
  38338. /**
  38339. * Makes sure binding's resource is visible for the given shader stage.
  38340. *
  38341. * @param {number} visibility - The shader stage.
  38342. */
  38343. setVisibility( visibility ) {
  38344. this.visibility |= visibility;
  38345. }
  38346. /**
  38347. * Clones the binding.
  38348. *
  38349. * @return {Binding} The cloned binding.
  38350. */
  38351. clone() {
  38352. return Object.assign( new this.constructor(), this );
  38353. }
  38354. }
  38355. /**
  38356. * This function is usually called with the length in bytes of an array buffer.
  38357. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  38358. *
  38359. * @function
  38360. * @param {number} floatLength - The buffer length.
  38361. * @return {number} The padded length.
  38362. */
  38363. function getFloatLength( floatLength ) {
  38364. // ensure chunk size alignment (STD140 layout)
  38365. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38366. }
  38367. /**
  38368. * Represents a buffer binding type.
  38369. *
  38370. * @private
  38371. * @abstract
  38372. * @augments Binding
  38373. */
  38374. class Buffer extends Binding {
  38375. /**
  38376. * Constructs a new buffer.
  38377. *
  38378. * @param {string} name - The buffer's name.
  38379. * @param {TypedArray} [buffer=null] - The buffer.
  38380. */
  38381. constructor( name, buffer = null ) {
  38382. super( name );
  38383. /**
  38384. * This flag can be used for type testing.
  38385. *
  38386. * @type {boolean}
  38387. * @readonly
  38388. * @default true
  38389. */
  38390. this.isBuffer = true;
  38391. /**
  38392. * The bytes per element.
  38393. *
  38394. * @type {number}
  38395. */
  38396. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38397. /**
  38398. * A reference to the internal buffer.
  38399. *
  38400. * @private
  38401. * @type {TypedArray}
  38402. */
  38403. this._buffer = buffer;
  38404. }
  38405. /**
  38406. * The buffer's byte length.
  38407. *
  38408. * @type {number}
  38409. * @readonly
  38410. */
  38411. get byteLength() {
  38412. return getFloatLength( this._buffer.byteLength );
  38413. }
  38414. /**
  38415. * A reference to the internal buffer.
  38416. *
  38417. * @type {Float32Array}
  38418. * @readonly
  38419. */
  38420. get buffer() {
  38421. return this._buffer;
  38422. }
  38423. /**
  38424. * Updates the binding.
  38425. *
  38426. * @return {boolean} Whether the buffer has been updated and must be
  38427. * uploaded to the GPU.
  38428. */
  38429. update() {
  38430. return true;
  38431. }
  38432. }
  38433. /**
  38434. * Represents a uniform buffer binding type.
  38435. *
  38436. * @private
  38437. * @augments Buffer
  38438. */
  38439. class UniformBuffer extends Buffer {
  38440. /**
  38441. * Constructs a new uniform buffer.
  38442. *
  38443. * @param {string} name - The buffer's name.
  38444. * @param {TypedArray} [buffer=null] - The buffer.
  38445. */
  38446. constructor( name, buffer = null ) {
  38447. super( name, buffer );
  38448. /**
  38449. * This flag can be used for type testing.
  38450. *
  38451. * @type {boolean}
  38452. * @readonly
  38453. * @default true
  38454. */
  38455. this.isUniformBuffer = true;
  38456. }
  38457. }
  38458. let _id$4 = 0;
  38459. /**
  38460. * A special form of uniform buffer binding type.
  38461. * It's buffer value is managed by a node object.
  38462. *
  38463. * @private
  38464. * @augments UniformBuffer
  38465. */
  38466. class NodeUniformBuffer extends UniformBuffer {
  38467. /**
  38468. * Constructs a new node-based uniform buffer.
  38469. *
  38470. * @param {BufferNode} nodeUniform - The uniform buffer node.
  38471. * @param {UniformGroupNode} groupNode - The uniform group node.
  38472. */
  38473. constructor( nodeUniform, groupNode ) {
  38474. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  38475. /**
  38476. * The uniform buffer node.
  38477. *
  38478. * @type {BufferNode}
  38479. */
  38480. this.nodeUniform = nodeUniform;
  38481. /**
  38482. * The uniform group node.
  38483. *
  38484. * @type {UniformGroupNode}
  38485. */
  38486. this.groupNode = groupNode;
  38487. }
  38488. /**
  38489. * The uniform buffer.
  38490. *
  38491. * @type {Float32Array}
  38492. */
  38493. get buffer() {
  38494. return this.nodeUniform.value;
  38495. }
  38496. }
  38497. /**
  38498. * This class represents a uniform buffer binding but with
  38499. * an API that allows to maintain individual uniform objects.
  38500. *
  38501. * @private
  38502. * @augments UniformBuffer
  38503. */
  38504. class UniformsGroup extends UniformBuffer {
  38505. /**
  38506. * Constructs a new uniforms group.
  38507. *
  38508. * @param {string} name - The group's name.
  38509. */
  38510. constructor( name ) {
  38511. super( name );
  38512. /**
  38513. * This flag can be used for type testing.
  38514. *
  38515. * @type {boolean}
  38516. * @readonly
  38517. * @default true
  38518. */
  38519. this.isUniformsGroup = true;
  38520. /**
  38521. * An array with the raw uniform values.
  38522. *
  38523. * @private
  38524. * @type {?Array<number>}
  38525. * @default null
  38526. */
  38527. this._values = null;
  38528. /**
  38529. * An array of uniform objects.
  38530. *
  38531. * The order of uniforms in this array must match the order of uniforms in the shader.
  38532. *
  38533. * @type {Array<Uniform>}
  38534. */
  38535. this.uniforms = [];
  38536. }
  38537. /**
  38538. * Adds a uniform to this group.
  38539. *
  38540. * @param {Uniform} uniform - The uniform to add.
  38541. * @return {UniformsGroup} A reference to this group.
  38542. */
  38543. addUniform( uniform ) {
  38544. this.uniforms.push( uniform );
  38545. return this;
  38546. }
  38547. /**
  38548. * Removes a uniform from this group.
  38549. *
  38550. * @param {Uniform} uniform - The uniform to remove.
  38551. * @return {UniformsGroup} A reference to this group.
  38552. */
  38553. removeUniform( uniform ) {
  38554. const index = this.uniforms.indexOf( uniform );
  38555. if ( index !== -1 ) {
  38556. this.uniforms.splice( index, 1 );
  38557. }
  38558. return this;
  38559. }
  38560. /**
  38561. * An array with the raw uniform values.
  38562. *
  38563. * @type {Array<number>}
  38564. */
  38565. get values() {
  38566. if ( this._values === null ) {
  38567. this._values = Array.from( this.buffer );
  38568. }
  38569. return this._values;
  38570. }
  38571. /**
  38572. * A Float32 array buffer with the uniform values.
  38573. *
  38574. * @type {Float32Array}
  38575. */
  38576. get buffer() {
  38577. let buffer = this._buffer;
  38578. if ( buffer === null ) {
  38579. const byteLength = this.byteLength;
  38580. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  38581. this._buffer = buffer;
  38582. }
  38583. return buffer;
  38584. }
  38585. /**
  38586. * The byte length of the buffer with correct buffer alignment.
  38587. *
  38588. * @type {number}
  38589. */
  38590. get byteLength() {
  38591. let offset = 0; // global buffer offset in bytes
  38592. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  38593. const uniform = this.uniforms[ i ];
  38594. const { boundary, itemSize } = uniform;
  38595. // offset within a single chunk in bytes
  38596. const chunkOffset = offset % GPU_CHUNK_BYTES;
  38597. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  38598. // conformance tests
  38599. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  38600. // check for chunk overflow
  38601. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  38602. } else if ( chunkOffset % boundary !== 0 ) {
  38603. // check for correct alignment
  38604. offset += ( chunkOffset % boundary );
  38605. }
  38606. uniform.offset = ( offset / this.bytesPerElement );
  38607. offset += ( itemSize * this.bytesPerElement );
  38608. }
  38609. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  38610. }
  38611. /**
  38612. * Updates this group by updating each uniform object of
  38613. * the internal uniform list. The uniform objects check if their
  38614. * values has actually changed so this method only returns
  38615. * `true` if there is a real value change.
  38616. *
  38617. * @return {boolean} Whether the uniforms have been updated and
  38618. * must be uploaded to the GPU.
  38619. */
  38620. update() {
  38621. let updated = false;
  38622. for ( const uniform of this.uniforms ) {
  38623. if ( this.updateByType( uniform ) === true ) {
  38624. updated = true;
  38625. }
  38626. }
  38627. return updated;
  38628. }
  38629. /**
  38630. * Updates a given uniform by calling an update method matching
  38631. * the uniforms type.
  38632. *
  38633. * @param {Uniform} uniform - The uniform to update.
  38634. * @return {boolean} Whether the uniform has been updated or not.
  38635. */
  38636. updateByType( uniform ) {
  38637. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  38638. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  38639. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  38640. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  38641. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  38642. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  38643. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  38644. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  38645. }
  38646. /**
  38647. * Updates a given Number uniform.
  38648. *
  38649. * @param {NumberUniform} uniform - The Number uniform.
  38650. * @return {boolean} Whether the uniform has been updated or not.
  38651. */
  38652. updateNumber( uniform ) {
  38653. let updated = false;
  38654. const a = this.values;
  38655. const v = uniform.getValue();
  38656. const offset = uniform.offset;
  38657. const type = uniform.getType();
  38658. if ( a[ offset ] !== v ) {
  38659. const b = this._getBufferForType( type );
  38660. b[ offset ] = a[ offset ] = v;
  38661. updated = true;
  38662. }
  38663. return updated;
  38664. }
  38665. /**
  38666. * Updates a given Vector2 uniform.
  38667. *
  38668. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  38669. * @return {boolean} Whether the uniform has been updated or not.
  38670. */
  38671. updateVector2( uniform ) {
  38672. let updated = false;
  38673. const a = this.values;
  38674. const v = uniform.getValue();
  38675. const offset = uniform.offset;
  38676. const type = uniform.getType();
  38677. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  38678. const b = this._getBufferForType( type );
  38679. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38680. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38681. updated = true;
  38682. }
  38683. return updated;
  38684. }
  38685. /**
  38686. * Updates a given Vector3 uniform.
  38687. *
  38688. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  38689. * @return {boolean} Whether the uniform has been updated or not.
  38690. */
  38691. updateVector3( uniform ) {
  38692. let updated = false;
  38693. const a = this.values;
  38694. const v = uniform.getValue();
  38695. const offset = uniform.offset;
  38696. const type = uniform.getType();
  38697. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  38698. const b = this._getBufferForType( type );
  38699. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38700. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38701. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38702. updated = true;
  38703. }
  38704. return updated;
  38705. }
  38706. /**
  38707. * Updates a given Vector4 uniform.
  38708. *
  38709. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  38710. * @return {boolean} Whether the uniform has been updated or not.
  38711. */
  38712. updateVector4( uniform ) {
  38713. let updated = false;
  38714. const a = this.values;
  38715. const v = uniform.getValue();
  38716. const offset = uniform.offset;
  38717. const type = uniform.getType();
  38718. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  38719. const b = this._getBufferForType( type );
  38720. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  38721. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  38722. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  38723. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  38724. updated = true;
  38725. }
  38726. return updated;
  38727. }
  38728. /**
  38729. * Updates a given Color uniform.
  38730. *
  38731. * @param {ColorUniform} uniform - The Color uniform.
  38732. * @return {boolean} Whether the uniform has been updated or not.
  38733. */
  38734. updateColor( uniform ) {
  38735. let updated = false;
  38736. const a = this.values;
  38737. const c = uniform.getValue();
  38738. const offset = uniform.offset;
  38739. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  38740. const b = this.buffer;
  38741. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  38742. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  38743. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  38744. updated = true;
  38745. }
  38746. return updated;
  38747. }
  38748. /**
  38749. * Updates a given Matrix3 uniform.
  38750. *
  38751. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  38752. * @return {boolean} Whether the uniform has been updated or not.
  38753. */
  38754. updateMatrix3( uniform ) {
  38755. let updated = false;
  38756. const a = this.values;
  38757. const e = uniform.getValue().elements;
  38758. const offset = uniform.offset;
  38759. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  38760. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  38761. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  38762. const b = this.buffer;
  38763. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  38764. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  38765. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  38766. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  38767. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  38768. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  38769. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  38770. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  38771. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  38772. updated = true;
  38773. }
  38774. return updated;
  38775. }
  38776. /**
  38777. * Updates a given Matrix4 uniform.
  38778. *
  38779. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  38780. * @return {boolean} Whether the uniform has been updated or not.
  38781. */
  38782. updateMatrix4( uniform ) {
  38783. let updated = false;
  38784. const a = this.values;
  38785. const e = uniform.getValue().elements;
  38786. const offset = uniform.offset;
  38787. if ( arraysEqual( a, e, offset ) === false ) {
  38788. const b = this.buffer;
  38789. b.set( e, offset );
  38790. setArray( a, e, offset );
  38791. updated = true;
  38792. }
  38793. return updated;
  38794. }
  38795. /**
  38796. * Returns a typed array that matches the given data type.
  38797. *
  38798. * @param {string} type - The data type.
  38799. * @return {TypedArray} The typed array.
  38800. */
  38801. _getBufferForType( type ) {
  38802. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  38803. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  38804. return this.buffer;
  38805. }
  38806. }
  38807. /**
  38808. * Sets the values of the second array to the first array.
  38809. *
  38810. * @private
  38811. * @param {TypedArray} a - The first array.
  38812. * @param {TypedArray} b - The second array.
  38813. * @param {number} offset - An index offset for the first array.
  38814. */
  38815. function setArray( a, b, offset ) {
  38816. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38817. a[ offset + i ] = b[ i ];
  38818. }
  38819. }
  38820. /**
  38821. * Returns `true` if the given arrays are equal.
  38822. *
  38823. * @private
  38824. * @param {TypedArray} a - The first array.
  38825. * @param {TypedArray} b - The second array.
  38826. * @param {number} offset - An index offset for the first array.
  38827. * @return {boolean} Whether the given arrays are equal or not.
  38828. */
  38829. function arraysEqual( a, b, offset ) {
  38830. for ( let i = 0, l = b.length; i < l; i ++ ) {
  38831. if ( a[ offset + i ] !== b[ i ] ) return false;
  38832. }
  38833. return true;
  38834. }
  38835. let _id$3 = 0;
  38836. /**
  38837. * A special form of uniforms group that represents
  38838. * the individual uniforms as node-based uniforms.
  38839. *
  38840. * @private
  38841. * @augments UniformsGroup
  38842. */
  38843. class NodeUniformsGroup extends UniformsGroup {
  38844. /**
  38845. * Constructs a new node-based uniforms group.
  38846. *
  38847. * @param {string} name - The group's name.
  38848. * @param {UniformGroupNode} groupNode - The uniform group node.
  38849. */
  38850. constructor( name, groupNode ) {
  38851. super( name );
  38852. /**
  38853. * The group's ID.
  38854. *
  38855. * @type {number}
  38856. */
  38857. this.id = _id$3 ++;
  38858. /**
  38859. * The uniform group node.
  38860. *
  38861. * @type {UniformGroupNode}
  38862. */
  38863. this.groupNode = groupNode;
  38864. /**
  38865. * This flag can be used for type testing.
  38866. *
  38867. * @type {boolean}
  38868. * @readonly
  38869. * @default true
  38870. */
  38871. this.isNodeUniformsGroup = true;
  38872. }
  38873. }
  38874. let _id$2 = 0;
  38875. /**
  38876. * Represents a sampled texture binding type.
  38877. *
  38878. * @private
  38879. * @augments Binding
  38880. */
  38881. class SampledTexture extends Binding {
  38882. /**
  38883. * Constructs a new sampled texture.
  38884. *
  38885. * @param {string} name - The sampled texture's name.
  38886. * @param {?Texture} texture - The texture this binding is referring to.
  38887. */
  38888. constructor( name, texture ) {
  38889. super( name );
  38890. /**
  38891. * This identifier.
  38892. *
  38893. * @type {number}
  38894. */
  38895. this.id = _id$2 ++;
  38896. /**
  38897. * The texture this binding is referring to.
  38898. *
  38899. * @type {?Texture}
  38900. */
  38901. this.texture = texture;
  38902. /**
  38903. * The binding's version.
  38904. *
  38905. * @type {number}
  38906. */
  38907. this.version = texture ? texture.version : 0;
  38908. /**
  38909. * Whether the texture is a storage texture or not.
  38910. *
  38911. * @type {boolean}
  38912. * @default false
  38913. */
  38914. this.store = false;
  38915. /**
  38916. * The binding's generation which is an additional version
  38917. * qualifier.
  38918. *
  38919. * @type {?number}
  38920. * @default null
  38921. */
  38922. this.generation = null;
  38923. /**
  38924. * This flag can be used for type testing.
  38925. *
  38926. * @type {boolean}
  38927. * @readonly
  38928. * @default true
  38929. */
  38930. this.isSampledTexture = true;
  38931. }
  38932. /**
  38933. * Returns `true` whether this binding requires an update for the
  38934. * given generation.
  38935. *
  38936. * @param {number} generation - The generation.
  38937. * @return {boolean} Whether an update is required or not.
  38938. */
  38939. needsBindingsUpdate( generation ) {
  38940. const { texture } = this;
  38941. if ( generation !== this.generation ) {
  38942. this.generation = generation;
  38943. return true;
  38944. }
  38945. return texture.isVideoTexture;
  38946. }
  38947. /**
  38948. * Updates the binding.
  38949. *
  38950. * @return {boolean} Whether the texture has been updated and must be
  38951. * uploaded to the GPU.
  38952. */
  38953. update() {
  38954. const { texture, version } = this;
  38955. if ( version !== texture.version ) {
  38956. this.version = texture.version;
  38957. return true;
  38958. }
  38959. return false;
  38960. }
  38961. }
  38962. /**
  38963. * A special form of sampled texture binding type.
  38964. * It's texture value is managed by a node object.
  38965. *
  38966. * @private
  38967. * @augments SampledTexture
  38968. */
  38969. class NodeSampledTexture extends SampledTexture {
  38970. /**
  38971. * Constructs a new node-based sampled texture.
  38972. *
  38973. * @param {string} name - The textures's name.
  38974. * @param {TextureNode} textureNode - The texture node.
  38975. * @param {UniformGroupNode} groupNode - The uniform group node.
  38976. * @param {?string} [access=null] - The access type.
  38977. */
  38978. constructor( name, textureNode, groupNode, access = null ) {
  38979. super( name, textureNode ? textureNode.value : null );
  38980. /**
  38981. * The texture node.
  38982. *
  38983. * @type {TextureNode}
  38984. */
  38985. this.textureNode = textureNode;
  38986. /**
  38987. * The uniform group node.
  38988. *
  38989. * @type {UniformGroupNode}
  38990. */
  38991. this.groupNode = groupNode;
  38992. /**
  38993. * The access type.
  38994. *
  38995. * @type {?string}
  38996. * @default null
  38997. */
  38998. this.access = access;
  38999. }
  39000. /**
  39001. * Overwrites the default to additionally check if the node value has changed.
  39002. *
  39003. * @param {number} generation - The generation.
  39004. * @return {boolean} Whether an update is required or not.
  39005. */
  39006. needsBindingsUpdate( generation ) {
  39007. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39008. }
  39009. /**
  39010. * Updates the binding.
  39011. *
  39012. * @return {boolean} Whether the texture has been updated and must be
  39013. * uploaded to the GPU.
  39014. */
  39015. update() {
  39016. const { textureNode } = this;
  39017. if ( this.texture !== textureNode.value ) {
  39018. this.texture = textureNode.value;
  39019. return true;
  39020. }
  39021. return super.update();
  39022. }
  39023. }
  39024. /**
  39025. * A special form of sampled cube texture binding type.
  39026. * It's texture value is managed by a node object.
  39027. *
  39028. * @private
  39029. * @augments NodeSampledTexture
  39030. */
  39031. class NodeSampledCubeTexture extends NodeSampledTexture {
  39032. /**
  39033. * Constructs a new node-based sampled cube texture.
  39034. *
  39035. * @param {string} name - The textures's name.
  39036. * @param {TextureNode} textureNode - The texture node.
  39037. * @param {UniformGroupNode} groupNode - The uniform group node.
  39038. * @param {?string} [access=null] - The access type.
  39039. */
  39040. constructor( name, textureNode, groupNode, access = null ) {
  39041. super( name, textureNode, groupNode, access );
  39042. /**
  39043. * This flag can be used for type testing.
  39044. *
  39045. * @type {boolean}
  39046. * @readonly
  39047. * @default true
  39048. */
  39049. this.isSampledCubeTexture = true;
  39050. }
  39051. }
  39052. /**
  39053. * A special form of sampled 3D texture binding type.
  39054. * It's texture value is managed by a node object.
  39055. *
  39056. * @private
  39057. * @augments NodeSampledTexture
  39058. */
  39059. class NodeSampledTexture3D extends NodeSampledTexture {
  39060. /**
  39061. * Constructs a new node-based sampled 3D texture.
  39062. *
  39063. * @param {string} name - The textures's name.
  39064. * @param {TextureNode} textureNode - The texture node.
  39065. * @param {UniformGroupNode} groupNode - The uniform group node.
  39066. * @param {?string} [access=null] - The access type.
  39067. */
  39068. constructor( name, textureNode, groupNode, access = null ) {
  39069. super( name, textureNode, groupNode, access );
  39070. /**
  39071. * This flag can be used for type testing.
  39072. *
  39073. * @type {boolean}
  39074. * @readonly
  39075. * @default true
  39076. */
  39077. this.isSampledTexture3D = true;
  39078. }
  39079. }
  39080. const glslMethods = {
  39081. textureDimensions: 'textureSize',
  39082. equals: 'equal'
  39083. };
  39084. const precisionLib = {
  39085. low: 'lowp',
  39086. medium: 'mediump',
  39087. high: 'highp'
  39088. };
  39089. const supports$1 = {
  39090. swizzleAssign: true,
  39091. storageBuffer: false
  39092. };
  39093. const interpolationTypeMap = {
  39094. perspective: 'smooth',
  39095. linear: 'noperspective'
  39096. };
  39097. const interpolationModeMap = {
  39098. 'centroid': 'centroid',
  39099. 'flat first': 'flat',
  39100. 'flat either': 'flat'
  39101. };
  39102. const defaultPrecisions = `
  39103. precision highp float;
  39104. precision highp int;
  39105. precision highp sampler2D;
  39106. precision highp sampler3D;
  39107. precision highp samplerCube;
  39108. precision highp sampler2DArray;
  39109. precision highp usampler2D;
  39110. precision highp usampler3D;
  39111. precision highp usamplerCube;
  39112. precision highp usampler2DArray;
  39113. precision highp isampler2D;
  39114. precision highp isampler3D;
  39115. precision highp isamplerCube;
  39116. precision highp isampler2DArray;
  39117. precision lowp sampler2DShadow;
  39118. precision lowp sampler2DArrayShadow;
  39119. precision lowp samplerCubeShadow;
  39120. `;
  39121. /**
  39122. * A node builder targeting GLSL.
  39123. *
  39124. * This module generates GLSL shader code from node materials and also
  39125. * generates the respective bindings and vertex buffer definitions. These
  39126. * data are later used by the renderer to create render and compute pipelines
  39127. * for render objects.
  39128. *
  39129. * @augments NodeBuilder
  39130. */
  39131. class GLSLNodeBuilder extends NodeBuilder {
  39132. /**
  39133. * Constructs a new GLSL node builder renderer.
  39134. *
  39135. * @param {Object3D} object - The 3D object.
  39136. * @param {Renderer} renderer - The renderer.
  39137. */
  39138. constructor( object, renderer ) {
  39139. super( object, renderer, new GLSLNodeParser() );
  39140. /**
  39141. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  39142. * another dictionary which manages UBOs per group ('render','frame','object').
  39143. *
  39144. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  39145. */
  39146. this.uniformGroups = {};
  39147. /**
  39148. * An array that holds objects defining the varying and attribute data in
  39149. * context of Transform Feedback.
  39150. *
  39151. * @type {Array<Object<string,AttributeNode|string>>}
  39152. */
  39153. this.transforms = [];
  39154. /**
  39155. * A dictionary that holds for each shader stage a Map of used extensions.
  39156. *
  39157. * @type {Object<string,Map<string,Object>>}
  39158. */
  39159. this.extensions = {};
  39160. /**
  39161. * A dictionary that holds for each shader stage an Array of used builtins.
  39162. *
  39163. * @type {Object<string,Array<string>>}
  39164. */
  39165. this.builtins = { vertex: [], fragment: [], compute: [] };
  39166. }
  39167. /**
  39168. * Checks if the given texture requires a manual conversion to the working color space.
  39169. *
  39170. * @param {Texture} texture - The texture to check.
  39171. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  39172. */
  39173. needsToWorkingColorSpace( texture ) {
  39174. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  39175. }
  39176. /**
  39177. * Returns the native shader method name for a given generic name.
  39178. *
  39179. * @param {string} method - The method name to resolve.
  39180. * @return {string} The resolved GLSL method name.
  39181. */
  39182. getMethod( method ) {
  39183. return glslMethods[ method ] || method;
  39184. }
  39185. /**
  39186. * Returns the output struct name. Not relevant for GLSL.
  39187. *
  39188. * @return {string}
  39189. */
  39190. getOutputStructName() {
  39191. return '';
  39192. }
  39193. /**
  39194. * Builds the given shader node.
  39195. *
  39196. * @param {ShaderNodeInternal} shaderNode - The shader node.
  39197. * @return {string} The GLSL function code.
  39198. */
  39199. buildFunctionCode( shaderNode ) {
  39200. const layout = shaderNode.layout;
  39201. const flowData = this.flowShaderNode( shaderNode );
  39202. const parameters = [];
  39203. for ( const input of layout.inputs ) {
  39204. parameters.push( this.getType( input.type ) + ' ' + input.name );
  39205. }
  39206. //
  39207. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  39208. ${ flowData.vars }
  39209. ${ flowData.code }
  39210. return ${ flowData.result };
  39211. }`;
  39212. //
  39213. return code;
  39214. }
  39215. /**
  39216. * Setups the Pixel Buffer Object (PBO) for the given storage
  39217. * buffer node.
  39218. *
  39219. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  39220. */
  39221. setupPBO( storageBufferNode ) {
  39222. const attribute = storageBufferNode.value;
  39223. if ( attribute.pbo === undefined ) {
  39224. const originalArray = attribute.array;
  39225. const numElements = attribute.count * attribute.itemSize;
  39226. const { itemSize } = attribute;
  39227. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  39228. let format = isInteger ? RedIntegerFormat : RedFormat;
  39229. if ( itemSize === 2 ) {
  39230. format = isInteger ? RGIntegerFormat : RGFormat;
  39231. } else if ( itemSize === 3 ) {
  39232. format = isInteger ? RGBIntegerFormat : RGBFormat;
  39233. } else if ( itemSize === 4 ) {
  39234. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  39235. }
  39236. const typeMap = {
  39237. Float32Array: FloatType,
  39238. Uint8Array: UnsignedByteType,
  39239. Uint16Array: UnsignedShortType,
  39240. Uint32Array: UnsignedIntType,
  39241. Int8Array: ByteType,
  39242. Int16Array: ShortType,
  39243. Int32Array: IntType,
  39244. Uint8ClampedArray: UnsignedByteType,
  39245. };
  39246. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  39247. let height = Math.ceil( ( numElements / itemSize ) / width );
  39248. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  39249. const newSize = width * height * itemSize;
  39250. const newArray = new originalArray.constructor( newSize );
  39251. newArray.set( originalArray, 0 );
  39252. attribute.array = newArray;
  39253. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  39254. pboTexture.needsUpdate = true;
  39255. pboTexture.isPBOTexture = true;
  39256. const pbo = new TextureNode( pboTexture, null, null );
  39257. pbo.setPrecision( 'high' );
  39258. attribute.pboNode = pbo;
  39259. attribute.pbo = pbo.value;
  39260. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39261. }
  39262. }
  39263. /**
  39264. * Returns a GLSL snippet that represents the property name of the given node.
  39265. *
  39266. * @param {Node} node - The node.
  39267. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39268. * @return {string} The property name.
  39269. */
  39270. getPropertyName( node, shaderStage = this.shaderStage ) {
  39271. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  39272. return shaderStage.charAt( 0 ) + '_' + node.name;
  39273. }
  39274. return super.getPropertyName( node, shaderStage );
  39275. }
  39276. /**
  39277. * Setups the Pixel Buffer Object (PBO) for the given storage
  39278. * buffer node.
  39279. *
  39280. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  39281. * @return {string} The property name.
  39282. */
  39283. generatePBO( storageArrayElementNode ) {
  39284. const { node, indexNode } = storageArrayElementNode;
  39285. const attribute = node.value;
  39286. if ( this.renderer.backend.has( attribute ) ) {
  39287. const attributeData = this.renderer.backend.get( attribute );
  39288. attributeData.pbo = attribute.pbo;
  39289. }
  39290. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39291. const textureName = this.getPropertyName( nodeUniform );
  39292. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  39293. const indexSnippet = indexNode.build( this, 'uint' );
  39294. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  39295. let propertyName = elementNodeData.propertyName;
  39296. if ( propertyName === undefined ) {
  39297. // property element
  39298. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  39299. propertyName = this.getPropertyName( nodeVar );
  39300. // property size
  39301. const bufferNodeData = this.getDataFromNode( node );
  39302. let propertySizeName = bufferNodeData.propertySizeName;
  39303. if ( propertySizeName === undefined ) {
  39304. propertySizeName = propertyName + 'Size';
  39305. this.getVarFromNode( node, propertySizeName, 'uint' );
  39306. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  39307. bufferNodeData.propertySizeName = propertySizeName;
  39308. }
  39309. //
  39310. const { itemSize } = attribute;
  39311. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  39312. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  39313. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  39314. //
  39315. let prefix = 'vec4';
  39316. if ( attribute.pbo.type === UnsignedIntType ) {
  39317. prefix = 'uvec4';
  39318. } else if ( attribute.pbo.type === IntType ) {
  39319. prefix = 'ivec4';
  39320. }
  39321. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  39322. elementNodeData.propertyName = propertyName;
  39323. }
  39324. return propertyName;
  39325. }
  39326. /**
  39327. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  39328. *
  39329. * @param {Texture} texture - The texture.
  39330. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39331. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39332. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39333. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39334. * @return {string} The GLSL snippet.
  39335. */
  39336. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  39337. if ( depthSnippet ) {
  39338. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  39339. } else {
  39340. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  39341. }
  39342. }
  39343. /**
  39344. * Generates the GLSL snippet for sampling/loading the given texture.
  39345. *
  39346. * @param {Texture} texture - The texture.
  39347. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39348. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39349. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39350. * @return {string} The GLSL snippet.
  39351. */
  39352. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  39353. if ( texture.isDepthTexture ) {
  39354. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  39355. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  39356. } else {
  39357. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  39358. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  39359. }
  39360. }
  39361. /**
  39362. * Generates the GLSL snippet when sampling textures with explicit mip level.
  39363. *
  39364. * @param {Texture} texture - The texture.
  39365. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39366. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39367. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39368. * @return {string} The GLSL snippet.
  39369. */
  39370. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  39371. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  39372. }
  39373. /**
  39374. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  39375. *
  39376. * @param {Texture} texture - The texture.
  39377. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39378. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39379. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  39380. * @return {string} The GLSL snippet.
  39381. */
  39382. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  39383. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  39384. }
  39385. /**
  39386. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  39387. *
  39388. * @param {Texture} texture - The texture.
  39389. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39390. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39391. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  39392. * @return {string} The GLSL snippet.
  39393. */
  39394. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  39395. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  39396. }
  39397. /**
  39398. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  39399. * against a reference value.
  39400. *
  39401. * @param {Texture} texture - The texture.
  39402. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39403. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39404. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  39405. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  39406. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39407. * @return {string} The GLSL snippet.
  39408. */
  39409. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  39410. if ( shaderStage === 'fragment' ) {
  39411. if ( depthSnippet ) {
  39412. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  39413. }
  39414. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  39415. } else {
  39416. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  39417. }
  39418. }
  39419. /**
  39420. * Returns the variables of the given shader stage as a GLSL string.
  39421. *
  39422. * @param {string} shaderStage - The shader stage.
  39423. * @return {string} The GLSL snippet that defines the variables.
  39424. */
  39425. getVars( shaderStage ) {
  39426. const snippets = [];
  39427. const vars = this.vars[ shaderStage ];
  39428. if ( vars !== undefined ) {
  39429. for ( const variable of vars ) {
  39430. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  39431. }
  39432. }
  39433. return snippets.join( '\n\t' );
  39434. }
  39435. /**
  39436. * Returns the uniforms of the given shader stage as a GLSL string.
  39437. *
  39438. * @param {string} shaderStage - The shader stage.
  39439. * @return {string} The GLSL snippet that defines the uniforms.
  39440. */
  39441. getUniforms( shaderStage ) {
  39442. const uniforms = this.uniforms[ shaderStage ];
  39443. const bindingSnippets = [];
  39444. const uniformGroups = {};
  39445. for ( const uniform of uniforms ) {
  39446. let snippet = null;
  39447. let group = false;
  39448. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  39449. const texture = uniform.node.value;
  39450. let typePrefix = '';
  39451. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  39452. if ( texture.type === UnsignedIntType ) {
  39453. typePrefix = 'u';
  39454. } else if ( texture.type === IntType ) {
  39455. typePrefix = 'i';
  39456. }
  39457. }
  39458. if ( uniform.type === 'texture3D' && texture.isTextureArray === false ) {
  39459. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  39460. } else if ( texture.compareFunction ) {
  39461. if ( texture.isDepthArrayTexture === true ) {
  39462. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  39463. } else {
  39464. snippet = `sampler2DShadow ${ uniform.name };`;
  39465. }
  39466. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true || texture.isTextureArray === true ) {
  39467. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  39468. } else {
  39469. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  39470. }
  39471. } else if ( uniform.type === 'cubeTexture' ) {
  39472. snippet = `samplerCube ${ uniform.name };`;
  39473. } else if ( uniform.type === 'buffer' ) {
  39474. const bufferNode = uniform.node;
  39475. const bufferType = this.getType( bufferNode.bufferType );
  39476. const bufferCount = bufferNode.bufferCount;
  39477. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  39478. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  39479. } else {
  39480. const vectorType = this.getVectorType( uniform.type );
  39481. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  39482. group = true;
  39483. }
  39484. const precision = uniform.node.precision;
  39485. if ( precision !== null ) {
  39486. snippet = precisionLib[ precision ] + ' ' + snippet;
  39487. }
  39488. if ( group ) {
  39489. snippet = '\t' + snippet;
  39490. const groupName = uniform.groupNode.name;
  39491. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  39492. groupSnippets.push( snippet );
  39493. } else {
  39494. snippet = 'uniform ' + snippet;
  39495. bindingSnippets.push( snippet );
  39496. }
  39497. }
  39498. let output = '';
  39499. for ( const name in uniformGroups ) {
  39500. const groupSnippets = uniformGroups[ name ];
  39501. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  39502. }
  39503. output += bindingSnippets.join( '\n' );
  39504. return output;
  39505. }
  39506. /**
  39507. * Returns the type for a given buffer attribute.
  39508. *
  39509. * @param {BufferAttribute} attribute - The buffer attribute.
  39510. * @return {string} The type.
  39511. */
  39512. getTypeFromAttribute( attribute ) {
  39513. let nodeType = super.getTypeFromAttribute( attribute );
  39514. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  39515. let dataAttribute = attribute;
  39516. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  39517. const array = dataAttribute.array;
  39518. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  39519. nodeType = nodeType.slice( 1 );
  39520. }
  39521. }
  39522. return nodeType;
  39523. }
  39524. /**
  39525. * Returns the shader attributes of the given shader stage as a GLSL string.
  39526. *
  39527. * @param {string} shaderStage - The shader stage.
  39528. * @return {string} The GLSL snippet that defines the shader attributes.
  39529. */
  39530. getAttributes( shaderStage ) {
  39531. let snippet = '';
  39532. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39533. const attributes = this.getAttributesArray();
  39534. let location = 0;
  39535. for ( const attribute of attributes ) {
  39536. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  39537. }
  39538. }
  39539. return snippet;
  39540. }
  39541. /**
  39542. * Returns the members of the given struct type node as a GLSL string.
  39543. *
  39544. * @param {StructTypeNode} struct - The struct type node.
  39545. * @return {string} The GLSL snippet that defines the struct members.
  39546. */
  39547. getStructMembers( struct ) {
  39548. const snippets = [];
  39549. for ( const member of struct.members ) {
  39550. snippets.push( `\t${ member.type } ${ member.name };` );
  39551. }
  39552. return snippets.join( '\n' );
  39553. }
  39554. /**
  39555. * Returns the structs of the given shader stage as a GLSL string.
  39556. *
  39557. * @param {string} shaderStage - The shader stage.
  39558. * @return {string} The GLSL snippet that defines the structs.
  39559. */
  39560. getStructs( shaderStage ) {
  39561. const snippets = [];
  39562. const structs = this.structs[ shaderStage ];
  39563. const outputSnippet = [];
  39564. for ( const struct of structs ) {
  39565. if ( struct.output ) {
  39566. for ( const member of struct.members ) {
  39567. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  39568. }
  39569. } else {
  39570. let snippet = 'struct ' + struct.name + ' {\n';
  39571. snippet += this.getStructMembers( struct );
  39572. snippet += '\n};\n';
  39573. snippets.push( snippet );
  39574. }
  39575. }
  39576. if ( outputSnippet.length === 0 ) {
  39577. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  39578. }
  39579. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  39580. }
  39581. /**
  39582. * Returns the varyings of the given shader stage as a GLSL string.
  39583. *
  39584. * @param {string} shaderStage - The shader stage.
  39585. * @return {string} The GLSL snippet that defines the varyings.
  39586. */
  39587. getVaryings( shaderStage ) {
  39588. let snippet = '';
  39589. const varyings = this.varyings;
  39590. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  39591. for ( const varying of varyings ) {
  39592. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  39593. const type = this.getType( varying.type );
  39594. if ( varying.needsInterpolation ) {
  39595. if ( varying.interpolationType ) {
  39596. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  39597. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  39598. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  39599. } else {
  39600. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39601. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  39602. }
  39603. } else {
  39604. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  39605. }
  39606. }
  39607. } else if ( shaderStage === 'fragment' ) {
  39608. for ( const varying of varyings ) {
  39609. if ( varying.needsInterpolation ) {
  39610. const type = this.getType( varying.type );
  39611. if ( varying.interpolationType ) {
  39612. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  39613. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  39614. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  39615. } else {
  39616. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  39617. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  39618. }
  39619. }
  39620. }
  39621. }
  39622. for ( const builtin of this.builtins[ shaderStage ] ) {
  39623. snippet += `${builtin};\n`;
  39624. }
  39625. return snippet;
  39626. }
  39627. /**
  39628. * Returns the vertex index builtin.
  39629. *
  39630. * @return {string} The vertex index.
  39631. */
  39632. getVertexIndex() {
  39633. return 'uint( gl_VertexID )';
  39634. }
  39635. /**
  39636. * Returns the instance index builtin.
  39637. *
  39638. * @return {string} The instance index.
  39639. */
  39640. getInstanceIndex() {
  39641. return 'uint( gl_InstanceID )';
  39642. }
  39643. /**
  39644. * Returns the invocation local index builtin.
  39645. *
  39646. * @return {string} The invocation local index.
  39647. */
  39648. getInvocationLocalIndex() {
  39649. const workgroupSize = this.object.workgroupSize;
  39650. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  39651. return `uint( gl_InstanceID ) % ${size}u`;
  39652. }
  39653. /**
  39654. * Returns the draw index builtin.
  39655. *
  39656. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  39657. */
  39658. getDrawIndex() {
  39659. const extensions = this.renderer.backend.extensions;
  39660. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  39661. return 'uint( gl_DrawID )';
  39662. }
  39663. return null;
  39664. }
  39665. /**
  39666. * Returns the front facing builtin.
  39667. *
  39668. * @return {string} The front facing builtin.
  39669. */
  39670. getFrontFacing() {
  39671. return 'gl_FrontFacing';
  39672. }
  39673. /**
  39674. * Returns the frag coord builtin.
  39675. *
  39676. * @return {string} The frag coord builtin.
  39677. */
  39678. getFragCoord() {
  39679. return 'gl_FragCoord.xy';
  39680. }
  39681. /**
  39682. * Returns the frag depth builtin.
  39683. *
  39684. * @return {string} The frag depth builtin.
  39685. */
  39686. getFragDepth() {
  39687. return 'gl_FragDepth';
  39688. }
  39689. /**
  39690. * Enables the given extension.
  39691. *
  39692. * @param {string} name - The extension name.
  39693. * @param {string} behavior - The extension behavior.
  39694. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  39695. */
  39696. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  39697. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  39698. if ( map.has( name ) === false ) {
  39699. map.set( name, {
  39700. name,
  39701. behavior
  39702. } );
  39703. }
  39704. }
  39705. /**
  39706. * Returns the enabled extensions of the given shader stage as a GLSL string.
  39707. *
  39708. * @param {string} shaderStage - The shader stage.
  39709. * @return {string} The GLSL snippet that defines the enabled extensions.
  39710. */
  39711. getExtensions( shaderStage ) {
  39712. const snippets = [];
  39713. if ( shaderStage === 'vertex' ) {
  39714. const ext = this.renderer.backend.extensions;
  39715. const isBatchedMesh = this.object.isBatchedMesh;
  39716. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  39717. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  39718. }
  39719. }
  39720. const extensions = this.extensions[ shaderStage ];
  39721. if ( extensions !== undefined ) {
  39722. for ( const { name, behavior } of extensions.values() ) {
  39723. snippets.push( `#extension ${name} : ${behavior}` );
  39724. }
  39725. }
  39726. return snippets.join( '\n' );
  39727. }
  39728. /**
  39729. * Returns the clip distances builtin.
  39730. *
  39731. * @return {string} The clip distances builtin.
  39732. */
  39733. getClipDistance() {
  39734. return 'gl_ClipDistance';
  39735. }
  39736. /**
  39737. * Whether the requested feature is available or not.
  39738. *
  39739. * @param {string} name - The requested feature.
  39740. * @return {boolean} Whether the requested feature is supported or not.
  39741. */
  39742. isAvailable( name ) {
  39743. let result = supports$1[ name ];
  39744. if ( result === undefined ) {
  39745. let extensionName;
  39746. result = false;
  39747. switch ( name ) {
  39748. case 'float32Filterable':
  39749. extensionName = 'OES_texture_float_linear';
  39750. break;
  39751. case 'clipDistance':
  39752. extensionName = 'WEBGL_clip_cull_distance';
  39753. break;
  39754. }
  39755. if ( extensionName !== undefined ) {
  39756. const extensions = this.renderer.backend.extensions;
  39757. if ( extensions.has( extensionName ) ) {
  39758. extensions.get( extensionName );
  39759. result = true;
  39760. }
  39761. }
  39762. supports$1[ name ] = result;
  39763. }
  39764. return result;
  39765. }
  39766. /**
  39767. * Whether to flip texture data along its vertical axis or not.
  39768. *
  39769. * @return {boolean} Returns always `true` in context of GLSL.
  39770. */
  39771. isFlipY() {
  39772. return true;
  39773. }
  39774. /**
  39775. * Enables hardware clipping.
  39776. *
  39777. * @param {string} planeCount - The clipping plane count.
  39778. */
  39779. enableHardwareClipping( planeCount ) {
  39780. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  39781. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  39782. }
  39783. /**
  39784. * Enables multiview.
  39785. */
  39786. enableMultiview() {
  39787. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  39788. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  39789. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  39790. }
  39791. /**
  39792. * Registers a transform in context of Transform Feedback.
  39793. *
  39794. * @param {string} varyingName - The varying name.
  39795. * @param {AttributeNode} attributeNode - The attribute node.
  39796. */
  39797. registerTransform( varyingName, attributeNode ) {
  39798. this.transforms.push( { varyingName, attributeNode } );
  39799. }
  39800. /**
  39801. * Returns the transforms of the given shader stage as a GLSL string.
  39802. *
  39803. * @param {string} shaderStage - The shader stage.
  39804. * @return {string} The GLSL snippet that defines the transforms.
  39805. */
  39806. getTransforms( /* shaderStage */ ) {
  39807. const transforms = this.transforms;
  39808. let snippet = '';
  39809. for ( let i = 0; i < transforms.length; i ++ ) {
  39810. const transform = transforms[ i ];
  39811. const attributeName = this.getPropertyName( transform.attributeNode );
  39812. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  39813. }
  39814. return snippet;
  39815. }
  39816. /**
  39817. * Returns a GLSL struct based on the given name and variables.
  39818. *
  39819. * @private
  39820. * @param {string} name - The struct name.
  39821. * @param {string} vars - The struct variables.
  39822. * @return {string} The GLSL snippet representing a struct.
  39823. */
  39824. _getGLSLUniformStruct( name, vars ) {
  39825. return `
  39826. layout( std140 ) uniform ${name} {
  39827. ${vars}
  39828. };`;
  39829. }
  39830. /**
  39831. * Returns a GLSL vertex shader based on the given shader data.
  39832. *
  39833. * @private
  39834. * @param {Object} shaderData - The shader data.
  39835. * @return {string} The vertex shader.
  39836. */
  39837. _getGLSLVertexCode( shaderData ) {
  39838. return `#version 300 es
  39839. ${ this.getSignature() }
  39840. // extensions
  39841. ${shaderData.extensions}
  39842. // precision
  39843. ${ defaultPrecisions }
  39844. // uniforms
  39845. ${shaderData.uniforms}
  39846. // varyings
  39847. ${shaderData.varyings}
  39848. // attributes
  39849. ${shaderData.attributes}
  39850. // codes
  39851. ${shaderData.codes}
  39852. void main() {
  39853. // vars
  39854. ${shaderData.vars}
  39855. // transforms
  39856. ${shaderData.transforms}
  39857. // flow
  39858. ${shaderData.flow}
  39859. gl_PointSize = 1.0;
  39860. }
  39861. `;
  39862. }
  39863. /**
  39864. * Returns a GLSL fragment shader based on the given shader data.
  39865. *
  39866. * @private
  39867. * @param {Object} shaderData - The shader data.
  39868. * @return {string} The vertex shader.
  39869. */
  39870. _getGLSLFragmentCode( shaderData ) {
  39871. return `#version 300 es
  39872. ${ this.getSignature() }
  39873. // extensions
  39874. ${shaderData.extensions}
  39875. // precision
  39876. ${ defaultPrecisions }
  39877. // uniforms
  39878. ${shaderData.uniforms}
  39879. // varyings
  39880. ${shaderData.varyings}
  39881. // codes
  39882. ${shaderData.codes}
  39883. // structs
  39884. ${shaderData.structs}
  39885. void main() {
  39886. // vars
  39887. ${shaderData.vars}
  39888. // flow
  39889. ${shaderData.flow}
  39890. }
  39891. `;
  39892. }
  39893. /**
  39894. * Controls the code build of the shader stages.
  39895. */
  39896. buildCode() {
  39897. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  39898. this.sortBindingGroups();
  39899. for ( const shaderStage in shadersData ) {
  39900. let flow = '// code\n\n';
  39901. flow += this.flowCode[ shaderStage ];
  39902. const flowNodes = this.flowNodes[ shaderStage ];
  39903. const mainNode = flowNodes[ flowNodes.length - 1 ];
  39904. for ( const node of flowNodes ) {
  39905. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  39906. const slotName = node.name;
  39907. if ( slotName ) {
  39908. if ( flow.length > 0 ) flow += '\n';
  39909. flow += `\t// flow -> ${ slotName }\n\t`;
  39910. }
  39911. flow += `${ flowSlotData.code }\n\t`;
  39912. if ( node === mainNode && shaderStage !== 'compute' ) {
  39913. flow += '// result\n\t';
  39914. if ( shaderStage === 'vertex' ) {
  39915. flow += 'gl_Position = ';
  39916. flow += `${ flowSlotData.result };`;
  39917. } else if ( shaderStage === 'fragment' ) {
  39918. if ( ! node.outputNode.isOutputStructNode ) {
  39919. flow += 'fragColor = ';
  39920. flow += `${ flowSlotData.result };`;
  39921. }
  39922. }
  39923. }
  39924. }
  39925. const stageData = shadersData[ shaderStage ];
  39926. stageData.extensions = this.getExtensions( shaderStage );
  39927. stageData.uniforms = this.getUniforms( shaderStage );
  39928. stageData.attributes = this.getAttributes( shaderStage );
  39929. stageData.varyings = this.getVaryings( shaderStage );
  39930. stageData.vars = this.getVars( shaderStage );
  39931. stageData.structs = this.getStructs( shaderStage );
  39932. stageData.codes = this.getCodes( shaderStage );
  39933. stageData.transforms = this.getTransforms( shaderStage );
  39934. stageData.flow = flow;
  39935. }
  39936. if ( this.material !== null ) {
  39937. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  39938. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  39939. } else {
  39940. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  39941. }
  39942. }
  39943. /**
  39944. * This method is one of the more important ones since it's responsible
  39945. * for generating a matching binding instance for the given uniform node.
  39946. *
  39947. * These bindings are later used in the renderer to create bind groups
  39948. * and layouts.
  39949. *
  39950. * @param {UniformNode} node - The uniform node.
  39951. * @param {string} type - The node data type.
  39952. * @param {string} shaderStage - The shader stage.
  39953. * @param {?string} [name=null] - An optional uniform name.
  39954. * @return {NodeUniform} The node uniform object.
  39955. */
  39956. getUniformFromNode( node, type, shaderStage, name = null ) {
  39957. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  39958. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  39959. let uniformGPU = nodeData.uniformGPU;
  39960. if ( uniformGPU === undefined ) {
  39961. const group = node.groupNode;
  39962. const groupName = group.name;
  39963. const bindings = this.getBindGroupArray( groupName, shaderStage );
  39964. if ( type === 'texture' ) {
  39965. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  39966. bindings.push( uniformGPU );
  39967. } else if ( type === 'cubeTexture' ) {
  39968. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  39969. bindings.push( uniformGPU );
  39970. } else if ( type === 'texture3D' ) {
  39971. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  39972. bindings.push( uniformGPU );
  39973. } else if ( type === 'buffer' ) {
  39974. node.name = `NodeBuffer_${ node.id }`;
  39975. uniformNode.name = `buffer${ node.id }`;
  39976. const buffer = new NodeUniformBuffer( node, group );
  39977. buffer.name = node.name;
  39978. bindings.push( buffer );
  39979. uniformGPU = buffer;
  39980. } else {
  39981. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  39982. let uniformsGroup = uniformsStage[ groupName ];
  39983. if ( uniformsGroup === undefined ) {
  39984. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  39985. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  39986. uniformsStage[ groupName ] = uniformsGroup;
  39987. bindings.push( uniformsGroup );
  39988. }
  39989. uniformGPU = this.getNodeUniform( uniformNode, type );
  39990. uniformsGroup.addUniform( uniformGPU );
  39991. }
  39992. nodeData.uniformGPU = uniformGPU;
  39993. }
  39994. return uniformNode;
  39995. }
  39996. }
  39997. let _vector2 = null;
  39998. let _color4 = null;
  39999. /**
  40000. * Most of the rendering related logic is implemented in the
  40001. * {@link Renderer} module and related management components.
  40002. * Sometimes it is required though to execute commands which are
  40003. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  40004. * This abstract base class defines an interface that encapsulates
  40005. * all backend-related logic. Derived classes for each backend must
  40006. * implement the interface.
  40007. *
  40008. * @abstract
  40009. * @private
  40010. */
  40011. class Backend {
  40012. /**
  40013. * Constructs a new backend.
  40014. *
  40015. * @param {Object} parameters - An object holding parameters for the backend.
  40016. */
  40017. constructor( parameters = {} ) {
  40018. /**
  40019. * The parameters of the backend.
  40020. *
  40021. * @type {Object}
  40022. */
  40023. this.parameters = Object.assign( {}, parameters );
  40024. /**
  40025. * This weak map holds backend-specific data of objects
  40026. * like textures, attributes or render targets.
  40027. *
  40028. * @type {WeakMap}
  40029. */
  40030. this.data = new WeakMap();
  40031. /**
  40032. * A reference to the renderer.
  40033. *
  40034. * @type {?Renderer}
  40035. * @default null
  40036. */
  40037. this.renderer = null;
  40038. /**
  40039. * A reference to the canvas element the renderer is drawing to.
  40040. *
  40041. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  40042. * @default null
  40043. */
  40044. this.domElement = null;
  40045. /**
  40046. * A reference to the timestamp query pool.
  40047. *
  40048. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  40049. */
  40050. this.timestampQueryPool = {
  40051. 'render': null,
  40052. 'compute': null
  40053. };
  40054. /**
  40055. * Whether to track timestamps with a Timestamp Query API or not.
  40056. *
  40057. * @type {boolean}
  40058. * @default false
  40059. */
  40060. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40061. }
  40062. /**
  40063. * Initializes the backend so it is ready for usage. Concrete backends
  40064. * are supposed to implement their rendering context creation and related
  40065. * operations in this method.
  40066. *
  40067. * @async
  40068. * @param {Renderer} renderer - The renderer.
  40069. * @return {Promise} A Promise that resolves when the backend has been initialized.
  40070. */
  40071. async init( renderer ) {
  40072. this.renderer = renderer;
  40073. }
  40074. /**
  40075. * The coordinate system of the backend.
  40076. *
  40077. * @abstract
  40078. * @type {number}
  40079. * @readonly
  40080. */
  40081. get coordinateSystem() {}
  40082. // render context
  40083. /**
  40084. * This method is executed at the beginning of a render call and
  40085. * can be used by the backend to prepare the state for upcoming
  40086. * draw calls.
  40087. *
  40088. * @abstract
  40089. * @param {RenderContext} renderContext - The render context.
  40090. */
  40091. beginRender( /*renderContext*/ ) {}
  40092. /**
  40093. * This method is executed at the end of a render call and
  40094. * can be used by the backend to finalize work after draw
  40095. * calls.
  40096. *
  40097. * @abstract
  40098. * @param {RenderContext} renderContext - The render context.
  40099. */
  40100. finishRender( /*renderContext*/ ) {}
  40101. /**
  40102. * This method is executed at the beginning of a compute call and
  40103. * can be used by the backend to prepare the state for upcoming
  40104. * compute tasks.
  40105. *
  40106. * @abstract
  40107. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40108. */
  40109. beginCompute( /*computeGroup*/ ) {}
  40110. /**
  40111. * This method is executed at the end of a compute call and
  40112. * can be used by the backend to finalize work after compute
  40113. * tasks.
  40114. *
  40115. * @abstract
  40116. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40117. */
  40118. finishCompute( /*computeGroup*/ ) {}
  40119. // render object
  40120. /**
  40121. * Executes a draw command for the given render object.
  40122. *
  40123. * @abstract
  40124. * @param {RenderObject} renderObject - The render object to draw.
  40125. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40126. */
  40127. draw( /*renderObject, info*/ ) { }
  40128. // compute node
  40129. /**
  40130. * Executes a compute command for the given compute node.
  40131. *
  40132. * @abstract
  40133. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  40134. * @param {Node} computeNode - The compute node.
  40135. * @param {Array<BindGroup>} bindings - The bindings.
  40136. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40137. */
  40138. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  40139. // program
  40140. /**
  40141. * Creates a shader program from the given programmable stage.
  40142. *
  40143. * @abstract
  40144. * @param {ProgrammableStage} program - The programmable stage.
  40145. */
  40146. createProgram( /*program*/ ) { }
  40147. /**
  40148. * Destroys the shader program of the given programmable stage.
  40149. *
  40150. * @abstract
  40151. * @param {ProgrammableStage} program - The programmable stage.
  40152. */
  40153. destroyProgram( /*program*/ ) { }
  40154. // bindings
  40155. /**
  40156. * Creates bindings from the given bind group definition.
  40157. *
  40158. * @abstract
  40159. * @param {BindGroup} bindGroup - The bind group.
  40160. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40161. * @param {number} cacheIndex - The cache index.
  40162. * @param {number} version - The version.
  40163. */
  40164. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40165. /**
  40166. * Updates the given bind group definition.
  40167. *
  40168. * @abstract
  40169. * @param {BindGroup} bindGroup - The bind group.
  40170. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40171. * @param {number} cacheIndex - The cache index.
  40172. * @param {number} version - The version.
  40173. */
  40174. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40175. /**
  40176. * Updates a buffer binding.
  40177. *
  40178. * @abstract
  40179. * @param {Buffer} binding - The buffer binding to update.
  40180. */
  40181. updateBinding( /*binding*/ ) { }
  40182. // pipeline
  40183. /**
  40184. * Creates a render pipeline for the given render object.
  40185. *
  40186. * @abstract
  40187. * @param {RenderObject} renderObject - The render object.
  40188. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  40189. */
  40190. createRenderPipeline( /*renderObject, promises*/ ) { }
  40191. /**
  40192. * Creates a compute pipeline for the given compute node.
  40193. *
  40194. * @abstract
  40195. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40196. * @param {Array<BindGroup>} bindings - The bindings.
  40197. */
  40198. createComputePipeline( /*computePipeline, bindings*/ ) { }
  40199. // cache key
  40200. /**
  40201. * Returns `true` if the render pipeline requires an update.
  40202. *
  40203. * @abstract
  40204. * @param {RenderObject} renderObject - The render object.
  40205. * @return {boolean} Whether the render pipeline requires an update or not.
  40206. */
  40207. needsRenderUpdate( /*renderObject*/ ) { }
  40208. /**
  40209. * Returns a cache key that is used to identify render pipelines.
  40210. *
  40211. * @abstract
  40212. * @param {RenderObject} renderObject - The render object.
  40213. * @return {string} The cache key.
  40214. */
  40215. getRenderCacheKey( /*renderObject*/ ) { }
  40216. // node builder
  40217. /**
  40218. * Returns a node builder for the given render object.
  40219. *
  40220. * @abstract
  40221. * @param {RenderObject} renderObject - The render object.
  40222. * @param {Renderer} renderer - The renderer.
  40223. * @return {NodeBuilder} The node builder.
  40224. */
  40225. createNodeBuilder( /*renderObject, renderer*/ ) { }
  40226. // textures
  40227. /**
  40228. * Creates a GPU sampler for the given texture.
  40229. *
  40230. * @abstract
  40231. * @param {Texture} texture - The texture to create the sampler for.
  40232. */
  40233. createSampler( /*texture*/ ) { }
  40234. /**
  40235. * Destroys the GPU sampler for the given texture.
  40236. *
  40237. * @abstract
  40238. * @param {Texture} texture - The texture to destroy the sampler for.
  40239. */
  40240. destroySampler( /*texture*/ ) {}
  40241. /**
  40242. * Creates a default texture for the given texture that can be used
  40243. * as a placeholder until the actual texture is ready for usage.
  40244. *
  40245. * @abstract
  40246. * @param {Texture} texture - The texture to create a default texture for.
  40247. */
  40248. createDefaultTexture( /*texture*/ ) { }
  40249. /**
  40250. * Defines a texture on the GPU for the given texture object.
  40251. *
  40252. * @abstract
  40253. * @param {Texture} texture - The texture.
  40254. * @param {Object} [options={}] - Optional configuration parameter.
  40255. */
  40256. createTexture( /*texture, options={}*/ ) { }
  40257. /**
  40258. * Uploads the updated texture data to the GPU.
  40259. *
  40260. * @abstract
  40261. * @param {Texture} texture - The texture.
  40262. * @param {Object} [options={}] - Optional configuration parameter.
  40263. */
  40264. updateTexture( /*texture, options = {}*/ ) { }
  40265. /**
  40266. * Generates mipmaps for the given texture.
  40267. *
  40268. * @abstract
  40269. * @param {Texture} texture - The texture.
  40270. */
  40271. generateMipmaps( /*texture*/ ) { }
  40272. /**
  40273. * Destroys the GPU data for the given texture object.
  40274. *
  40275. * @abstract
  40276. * @param {Texture} texture - The texture.
  40277. */
  40278. destroyTexture( /*texture*/ ) { }
  40279. /**
  40280. * Returns texture data as a typed array.
  40281. *
  40282. * @abstract
  40283. * @async
  40284. * @param {Texture} texture - The texture to copy.
  40285. * @param {number} x - The x coordinate of the copy origin.
  40286. * @param {number} y - The y coordinate of the copy origin.
  40287. * @param {number} width - The width of the copy.
  40288. * @param {number} height - The height of the copy.
  40289. * @param {number} faceIndex - The face index.
  40290. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40291. */
  40292. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  40293. /**
  40294. * Copies data of the given source texture to the given destination texture.
  40295. *
  40296. * @abstract
  40297. * @param {Texture} srcTexture - The source texture.
  40298. * @param {Texture} dstTexture - The destination texture.
  40299. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  40300. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  40301. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40302. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40303. */
  40304. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  40305. /**
  40306. * Copies the current bound framebuffer to the given texture.
  40307. *
  40308. * @abstract
  40309. * @param {Texture} texture - The destination texture.
  40310. * @param {RenderContext} renderContext - The render context.
  40311. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40312. */
  40313. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  40314. // attributes
  40315. /**
  40316. * Creates the GPU buffer of a shader attribute.
  40317. *
  40318. * @abstract
  40319. * @param {BufferAttribute} attribute - The buffer attribute.
  40320. */
  40321. createAttribute( /*attribute*/ ) { }
  40322. /**
  40323. * Creates the GPU buffer of an indexed shader attribute.
  40324. *
  40325. * @abstract
  40326. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  40327. */
  40328. createIndexAttribute( /*attribute*/ ) { }
  40329. /**
  40330. * Creates the GPU buffer of a storage attribute.
  40331. *
  40332. * @abstract
  40333. * @param {BufferAttribute} attribute - The buffer attribute.
  40334. */
  40335. createStorageAttribute( /*attribute*/ ) { }
  40336. /**
  40337. * Updates the GPU buffer of a shader attribute.
  40338. *
  40339. * @abstract
  40340. * @param {BufferAttribute} attribute - The buffer attribute to update.
  40341. */
  40342. updateAttribute( /*attribute*/ ) { }
  40343. /**
  40344. * Destroys the GPU buffer of a shader attribute.
  40345. *
  40346. * @abstract
  40347. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  40348. */
  40349. destroyAttribute( /*attribute*/ ) { }
  40350. // canvas
  40351. /**
  40352. * Returns the backend's rendering context.
  40353. *
  40354. * @abstract
  40355. * @return {Object} The rendering context.
  40356. */
  40357. getContext() { }
  40358. /**
  40359. * Backends can use this method if they have to run
  40360. * logic when the renderer gets resized.
  40361. *
  40362. * @abstract
  40363. */
  40364. updateSize() { }
  40365. /**
  40366. * Updates the viewport with the values from the given render context.
  40367. *
  40368. * @abstract
  40369. * @param {RenderContext} renderContext - The render context.
  40370. */
  40371. updateViewport( /*renderContext*/ ) {}
  40372. // utils
  40373. /**
  40374. * Returns `true` if the given 3D object is fully occluded by other
  40375. * 3D objects in the scene. Backends must implement this method by using
  40376. * a Occlusion Query API.
  40377. *
  40378. * @abstract
  40379. * @param {RenderContext} renderContext - The render context.
  40380. * @param {Object3D} object - The 3D object to test.
  40381. * @return {boolean} Whether the 3D object is fully occluded or not.
  40382. */
  40383. isOccluded( /*renderContext, object*/ ) {}
  40384. /**
  40385. * Resolves the time stamp for the given render context and type.
  40386. *
  40387. * @async
  40388. * @abstract
  40389. * @param {string} [type='render'] - The type of the time stamp.
  40390. * @return {Promise<number>} A Promise that resolves with the time stamp.
  40391. */
  40392. async resolveTimestampsAsync( type = 'render' ) {
  40393. if ( ! this.trackTimestamp ) {
  40394. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  40395. return;
  40396. }
  40397. const queryPool = this.timestampQueryPool[ type ];
  40398. if ( ! queryPool ) {
  40399. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  40400. return;
  40401. }
  40402. const duration = await queryPool.resolveQueriesAsync();
  40403. this.renderer.info[ type ].timestamp = duration;
  40404. return duration;
  40405. }
  40406. /**
  40407. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40408. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40409. *
  40410. * @async
  40411. * @abstract
  40412. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40413. */
  40414. async waitForGPU() {}
  40415. /**
  40416. * This method performs a readback operation by moving buffer data from
  40417. * a storage buffer attribute from the GPU to the CPU.
  40418. *
  40419. * @async
  40420. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40421. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40422. */
  40423. async getArrayBufferAsync( /* attribute */ ) {}
  40424. /**
  40425. * Checks if the given feature is supported by the backend.
  40426. *
  40427. * @async
  40428. * @abstract
  40429. * @param {string} name - The feature's name.
  40430. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40431. */
  40432. async hasFeatureAsync( /*name*/ ) { }
  40433. /**
  40434. * Checks if the given feature is supported by the backend.
  40435. *
  40436. * @abstract
  40437. * @param {string} name - The feature's name.
  40438. * @return {boolean} Whether the feature is supported or not.
  40439. */
  40440. hasFeature( /*name*/ ) {}
  40441. /**
  40442. * Returns the maximum anisotropy texture filtering value.
  40443. *
  40444. * @abstract
  40445. * @return {number} The maximum anisotropy texture filtering value.
  40446. */
  40447. getMaxAnisotropy() {}
  40448. /**
  40449. * Returns the drawing buffer size.
  40450. *
  40451. * @return {Vector2} The drawing buffer size.
  40452. */
  40453. getDrawingBufferSize() {
  40454. _vector2 = _vector2 || new Vector2();
  40455. return this.renderer.getDrawingBufferSize( _vector2 );
  40456. }
  40457. /**
  40458. * Defines the scissor test.
  40459. *
  40460. * @abstract
  40461. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  40462. */
  40463. setScissorTest( /*boolean*/ ) { }
  40464. /**
  40465. * Returns the clear color and alpha into a single
  40466. * color object.
  40467. *
  40468. * @return {Color4} The clear color.
  40469. */
  40470. getClearColor() {
  40471. const renderer = this.renderer;
  40472. _color4 = _color4 || new Color4();
  40473. renderer.getClearColor( _color4 );
  40474. _color4.getRGB( _color4 );
  40475. return _color4;
  40476. }
  40477. /**
  40478. * Returns the DOM element. If no DOM element exists, the backend
  40479. * creates a new one.
  40480. *
  40481. * @return {HTMLCanvasElement} The DOM element.
  40482. */
  40483. getDomElement() {
  40484. let domElement = this.domElement;
  40485. if ( domElement === null ) {
  40486. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  40487. // OffscreenCanvas does not have setAttribute, see #22811
  40488. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  40489. this.domElement = domElement;
  40490. }
  40491. return domElement;
  40492. }
  40493. /**
  40494. * Sets a dictionary for the given object into the
  40495. * internal data structure.
  40496. *
  40497. * @param {Object} object - The object.
  40498. * @param {Object} value - The dictionary to set.
  40499. */
  40500. set( object, value ) {
  40501. this.data.set( object, value );
  40502. }
  40503. /**
  40504. * Returns the dictionary for the given object.
  40505. *
  40506. * @param {Object} object - The object.
  40507. * @return {Object} The object's dictionary.
  40508. */
  40509. get( object ) {
  40510. let map = this.data.get( object );
  40511. if ( map === undefined ) {
  40512. map = {};
  40513. this.data.set( object, map );
  40514. }
  40515. return map;
  40516. }
  40517. /**
  40518. * Checks if the given object has a dictionary
  40519. * with data defined.
  40520. *
  40521. * @param {Object} object - The object.
  40522. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  40523. */
  40524. has( object ) {
  40525. return this.data.has( object );
  40526. }
  40527. /**
  40528. * Deletes an object from the internal data structure.
  40529. *
  40530. * @param {Object} object - The object to delete.
  40531. */
  40532. delete( object ) {
  40533. this.data.delete( object );
  40534. }
  40535. /**
  40536. * Frees internal resources.
  40537. *
  40538. * @abstract
  40539. */
  40540. dispose() { }
  40541. }
  40542. let _id$1 = 0;
  40543. /**
  40544. * This module is internally used in context of compute shaders.
  40545. * This type of shader is not natively supported in WebGL 2 and
  40546. * thus implemented via Transform Feedback. `DualAttributeData`
  40547. * manages the related data.
  40548. *
  40549. * @private
  40550. */
  40551. class DualAttributeData {
  40552. constructor( attributeData, dualBuffer ) {
  40553. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  40554. this.type = attributeData.type;
  40555. this.bufferType = attributeData.bufferType;
  40556. this.pbo = attributeData.pbo;
  40557. this.byteLength = attributeData.byteLength;
  40558. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  40559. this.version = attributeData.version;
  40560. this.isInteger = attributeData.isInteger;
  40561. this.activeBufferIndex = 0;
  40562. this.baseId = attributeData.id;
  40563. }
  40564. get id() {
  40565. return `${ this.baseId }|${ this.activeBufferIndex }`;
  40566. }
  40567. get bufferGPU() {
  40568. return this.buffers[ this.activeBufferIndex ];
  40569. }
  40570. get transformBuffer() {
  40571. return this.buffers[ this.activeBufferIndex ^ 1 ];
  40572. }
  40573. switchBuffers() {
  40574. this.activeBufferIndex ^= 1;
  40575. }
  40576. }
  40577. /**
  40578. * A WebGL 2 backend utility module for managing shader attributes.
  40579. *
  40580. * @private
  40581. */
  40582. class WebGLAttributeUtils {
  40583. /**
  40584. * Constructs a new utility object.
  40585. *
  40586. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40587. */
  40588. constructor( backend ) {
  40589. /**
  40590. * A reference to the WebGL 2 backend.
  40591. *
  40592. * @type {WebGLBackend}
  40593. */
  40594. this.backend = backend;
  40595. }
  40596. /**
  40597. * Creates the GPU buffer for the given buffer attribute.
  40598. *
  40599. * @param {BufferAttribute} attribute - The buffer attribute.
  40600. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  40601. */
  40602. createAttribute( attribute, bufferType ) {
  40603. const backend = this.backend;
  40604. const { gl } = backend;
  40605. const array = attribute.array;
  40606. const usage = attribute.usage || gl.STATIC_DRAW;
  40607. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40608. const bufferData = backend.get( bufferAttribute );
  40609. let bufferGPU = bufferData.bufferGPU;
  40610. if ( bufferGPU === undefined ) {
  40611. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  40612. bufferData.bufferGPU = bufferGPU;
  40613. bufferData.bufferType = bufferType;
  40614. bufferData.version = bufferAttribute.version;
  40615. }
  40616. //attribute.onUploadCallback();
  40617. let type;
  40618. if ( array instanceof Float32Array ) {
  40619. type = gl.FLOAT;
  40620. } else if ( array instanceof Uint16Array ) {
  40621. if ( attribute.isFloat16BufferAttribute ) {
  40622. type = gl.HALF_FLOAT;
  40623. } else {
  40624. type = gl.UNSIGNED_SHORT;
  40625. }
  40626. } else if ( array instanceof Int16Array ) {
  40627. type = gl.SHORT;
  40628. } else if ( array instanceof Uint32Array ) {
  40629. type = gl.UNSIGNED_INT;
  40630. } else if ( array instanceof Int32Array ) {
  40631. type = gl.INT;
  40632. } else if ( array instanceof Int8Array ) {
  40633. type = gl.BYTE;
  40634. } else if ( array instanceof Uint8Array ) {
  40635. type = gl.UNSIGNED_BYTE;
  40636. } else if ( array instanceof Uint8ClampedArray ) {
  40637. type = gl.UNSIGNED_BYTE;
  40638. } else {
  40639. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  40640. }
  40641. let attributeData = {
  40642. bufferGPU,
  40643. bufferType,
  40644. type,
  40645. byteLength: array.byteLength,
  40646. bytesPerElement: array.BYTES_PER_ELEMENT,
  40647. version: attribute.version,
  40648. pbo: attribute.pbo,
  40649. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  40650. id: _id$1 ++
  40651. };
  40652. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  40653. // create buffer for transform feedback use
  40654. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  40655. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  40656. }
  40657. backend.set( attribute, attributeData );
  40658. }
  40659. /**
  40660. * Updates the GPU buffer of the given buffer attribute.
  40661. *
  40662. * @param {BufferAttribute} attribute - The buffer attribute.
  40663. */
  40664. updateAttribute( attribute ) {
  40665. const backend = this.backend;
  40666. const { gl } = backend;
  40667. const array = attribute.array;
  40668. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40669. const bufferData = backend.get( bufferAttribute );
  40670. const bufferType = bufferData.bufferType;
  40671. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  40672. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  40673. if ( updateRanges.length === 0 ) {
  40674. // Not using update ranges
  40675. gl.bufferSubData( bufferType, 0, array );
  40676. } else {
  40677. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  40678. const range = updateRanges[ i ];
  40679. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  40680. array, range.start, range.count );
  40681. }
  40682. bufferAttribute.clearUpdateRanges();
  40683. }
  40684. gl.bindBuffer( bufferType, null );
  40685. bufferData.version = bufferAttribute.version;
  40686. }
  40687. /**
  40688. * Destroys the GPU buffer of the given buffer attribute.
  40689. *
  40690. * @param {BufferAttribute} attribute - The buffer attribute.
  40691. */
  40692. destroyAttribute( attribute ) {
  40693. const backend = this.backend;
  40694. const { gl } = backend;
  40695. if ( attribute.isInterleavedBufferAttribute ) {
  40696. backend.delete( attribute.data );
  40697. }
  40698. const attributeData = backend.get( attribute );
  40699. gl.deleteBuffer( attributeData.bufferGPU );
  40700. backend.delete( attribute );
  40701. }
  40702. /**
  40703. * This method performs a readback operation by moving buffer data from
  40704. * a storage buffer attribute from the GPU to the CPU.
  40705. *
  40706. * @async
  40707. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40708. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40709. */
  40710. async getArrayBufferAsync( attribute ) {
  40711. const backend = this.backend;
  40712. const { gl } = backend;
  40713. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  40714. const { bufferGPU } = backend.get( bufferAttribute );
  40715. const array = attribute.array;
  40716. const byteLength = array.byteLength;
  40717. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  40718. const writeBuffer = gl.createBuffer();
  40719. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  40720. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  40721. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  40722. await backend.utils._clientWaitAsync();
  40723. const dstBuffer = new attribute.array.constructor( array.length );
  40724. // Ensure the buffer is bound before reading
  40725. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  40726. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  40727. gl.deleteBuffer( writeBuffer );
  40728. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  40729. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  40730. return dstBuffer.buffer;
  40731. }
  40732. /**
  40733. * Creates a WebGL buffer with the given data.
  40734. *
  40735. * @private
  40736. * @param {WebGL2RenderingContext} gl - The rendering context.
  40737. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  40738. * @param {TypedArray} array - The array of the buffer attribute.
  40739. * @param {GLenum} usage - The usage.
  40740. * @return {WebGLBuffer} The WebGL buffer.
  40741. */
  40742. _createBuffer( gl, bufferType, array, usage ) {
  40743. const bufferGPU = gl.createBuffer();
  40744. gl.bindBuffer( bufferType, bufferGPU );
  40745. gl.bufferData( bufferType, array, usage );
  40746. gl.bindBuffer( bufferType, null );
  40747. return bufferGPU;
  40748. }
  40749. }
  40750. let equationToGL, factorToGL;
  40751. /**
  40752. * A WebGL 2 backend utility module for managing the WebGL state.
  40753. *
  40754. * The major goal of this module is to reduce the number of state changes
  40755. * by caching the WEbGL state with a series of variables. In this way, the
  40756. * renderer only executes state change commands when necessary which
  40757. * improves the overall performance.
  40758. *
  40759. * @private
  40760. */
  40761. class WebGLState {
  40762. /**
  40763. * Constructs a new utility object.
  40764. *
  40765. * @param {WebGLBackend} backend - The WebGL 2 backend.
  40766. */
  40767. constructor( backend ) {
  40768. /**
  40769. * A reference to the WebGL 2 backend.
  40770. *
  40771. * @type {WebGLBackend}
  40772. */
  40773. this.backend = backend;
  40774. /**
  40775. * A reference to the rendering context.
  40776. *
  40777. * @type {WebGL2RenderingContext}
  40778. */
  40779. this.gl = this.backend.gl;
  40780. // Below properties are intended to cache
  40781. // the WebGL state and are not explicitly
  40782. // documented for convenience reasons.
  40783. this.enabled = {};
  40784. this.currentFlipSided = null;
  40785. this.currentCullFace = null;
  40786. this.currentProgram = null;
  40787. this.currentBlendingEnabled = false;
  40788. this.currentBlending = null;
  40789. this.currentBlendSrc = null;
  40790. this.currentBlendDst = null;
  40791. this.currentBlendSrcAlpha = null;
  40792. this.currentBlendDstAlpha = null;
  40793. this.currentPremultipledAlpha = null;
  40794. this.currentPolygonOffsetFactor = null;
  40795. this.currentPolygonOffsetUnits = null;
  40796. this.currentColorMask = null;
  40797. this.currentDepthFunc = null;
  40798. this.currentDepthMask = null;
  40799. this.currentStencilFunc = null;
  40800. this.currentStencilRef = null;
  40801. this.currentStencilFuncMask = null;
  40802. this.currentStencilFail = null;
  40803. this.currentStencilZFail = null;
  40804. this.currentStencilZPass = null;
  40805. this.currentStencilMask = null;
  40806. this.currentLineWidth = null;
  40807. this.currentClippingPlanes = 0;
  40808. this.currentVAO = null;
  40809. this.currentIndex = null;
  40810. this.currentBoundFramebuffers = {};
  40811. this.currentDrawbuffers = new WeakMap();
  40812. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  40813. this.currentTextureSlot = null;
  40814. this.currentBoundTextures = {};
  40815. this.currentBoundBufferBases = {};
  40816. this._init();
  40817. }
  40818. /**
  40819. * Inits the state of the utility.
  40820. *
  40821. * @private
  40822. */
  40823. _init() {
  40824. const gl = this.gl;
  40825. // Store only WebGL constants here.
  40826. equationToGL = {
  40827. [ AddEquation ]: gl.FUNC_ADD,
  40828. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  40829. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  40830. };
  40831. factorToGL = {
  40832. [ ZeroFactor ]: gl.ZERO,
  40833. [ OneFactor ]: gl.ONE,
  40834. [ SrcColorFactor ]: gl.SRC_COLOR,
  40835. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  40836. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  40837. [ DstColorFactor ]: gl.DST_COLOR,
  40838. [ DstAlphaFactor ]: gl.DST_ALPHA,
  40839. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  40840. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  40841. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  40842. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  40843. };
  40844. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  40845. const viewportParam = gl.getParameter( gl.VIEWPORT );
  40846. this.currentScissor = new Vector4().fromArray( scissorParam );
  40847. this.currentViewport = new Vector4().fromArray( viewportParam );
  40848. this._tempVec4 = new Vector4();
  40849. }
  40850. /**
  40851. * Enables the given WebGL capability.
  40852. *
  40853. * This method caches the capability state so
  40854. * `gl.enable()` is only called when necessary.
  40855. *
  40856. * @param {GLenum} id - The capability to enable.
  40857. */
  40858. enable( id ) {
  40859. const { enabled } = this;
  40860. if ( enabled[ id ] !== true ) {
  40861. this.gl.enable( id );
  40862. enabled[ id ] = true;
  40863. }
  40864. }
  40865. /**
  40866. * Disables the given WebGL capability.
  40867. *
  40868. * This method caches the capability state so
  40869. * `gl.disable()` is only called when necessary.
  40870. *
  40871. * @param {GLenum} id - The capability to enable.
  40872. */
  40873. disable( id ) {
  40874. const { enabled } = this;
  40875. if ( enabled[ id ] !== false ) {
  40876. this.gl.disable( id );
  40877. enabled[ id ] = false;
  40878. }
  40879. }
  40880. /**
  40881. * Specifies whether polygons are front- or back-facing
  40882. * by setting the winding orientation.
  40883. *
  40884. * This method caches the state so `gl.frontFace()` is only
  40885. * called when necessary.
  40886. *
  40887. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  40888. */
  40889. setFlipSided( flipSided ) {
  40890. if ( this.currentFlipSided !== flipSided ) {
  40891. const { gl } = this;
  40892. if ( flipSided ) {
  40893. gl.frontFace( gl.CW );
  40894. } else {
  40895. gl.frontFace( gl.CCW );
  40896. }
  40897. this.currentFlipSided = flipSided;
  40898. }
  40899. }
  40900. /**
  40901. * Specifies whether or not front- and/or back-facing
  40902. * polygons can be culled.
  40903. *
  40904. * This method caches the state so `gl.cullFace()` is only
  40905. * called when necessary.
  40906. *
  40907. * @param {number} cullFace - Defines which polygons are candidates for culling.
  40908. */
  40909. setCullFace( cullFace ) {
  40910. const { gl } = this;
  40911. if ( cullFace !== CullFaceNone ) {
  40912. this.enable( gl.CULL_FACE );
  40913. if ( cullFace !== this.currentCullFace ) {
  40914. if ( cullFace === CullFaceBack ) {
  40915. gl.cullFace( gl.BACK );
  40916. } else if ( cullFace === CullFaceFront ) {
  40917. gl.cullFace( gl.FRONT );
  40918. } else {
  40919. gl.cullFace( gl.FRONT_AND_BACK );
  40920. }
  40921. }
  40922. } else {
  40923. this.disable( gl.CULL_FACE );
  40924. }
  40925. this.currentCullFace = cullFace;
  40926. }
  40927. /**
  40928. * Specifies the width of line primitives.
  40929. *
  40930. * This method caches the state so `gl.lineWidth()` is only
  40931. * called when necessary.
  40932. *
  40933. * @param {number} width - The line width.
  40934. */
  40935. setLineWidth( width ) {
  40936. const { currentLineWidth, gl } = this;
  40937. if ( width !== currentLineWidth ) {
  40938. gl.lineWidth( width );
  40939. this.currentLineWidth = width;
  40940. }
  40941. }
  40942. /**
  40943. * Defines the blending.
  40944. *
  40945. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  40946. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  40947. *
  40948. * @param {number} blending - The blending type.
  40949. * @param {number} blendEquation - The blending equation.
  40950. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  40951. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  40952. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  40953. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  40954. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  40955. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  40956. */
  40957. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  40958. const { gl } = this;
  40959. if ( blending === NoBlending ) {
  40960. if ( this.currentBlendingEnabled === true ) {
  40961. this.disable( gl.BLEND );
  40962. this.currentBlendingEnabled = false;
  40963. }
  40964. return;
  40965. }
  40966. if ( this.currentBlendingEnabled === false ) {
  40967. this.enable( gl.BLEND );
  40968. this.currentBlendingEnabled = true;
  40969. }
  40970. if ( blending !== CustomBlending ) {
  40971. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  40972. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  40973. gl.blendEquation( gl.FUNC_ADD );
  40974. this.currentBlendEquation = AddEquation;
  40975. this.currentBlendEquationAlpha = AddEquation;
  40976. }
  40977. if ( premultipliedAlpha ) {
  40978. switch ( blending ) {
  40979. case NormalBlending:
  40980. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40981. break;
  40982. case AdditiveBlending:
  40983. gl.blendFunc( gl.ONE, gl.ONE );
  40984. break;
  40985. case SubtractiveBlending:
  40986. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  40987. break;
  40988. case MultiplyBlending:
  40989. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  40990. break;
  40991. default:
  40992. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  40993. break;
  40994. }
  40995. } else {
  40996. switch ( blending ) {
  40997. case NormalBlending:
  40998. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  40999. break;
  41000. case AdditiveBlending:
  41001. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  41002. break;
  41003. case SubtractiveBlending:
  41004. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41005. break;
  41006. case MultiplyBlending:
  41007. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  41008. break;
  41009. default:
  41010. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41011. break;
  41012. }
  41013. }
  41014. this.currentBlendSrc = null;
  41015. this.currentBlendDst = null;
  41016. this.currentBlendSrcAlpha = null;
  41017. this.currentBlendDstAlpha = null;
  41018. this.currentBlending = blending;
  41019. this.currentPremultipledAlpha = premultipliedAlpha;
  41020. }
  41021. return;
  41022. }
  41023. // custom blending
  41024. blendEquationAlpha = blendEquationAlpha || blendEquation;
  41025. blendSrcAlpha = blendSrcAlpha || blendSrc;
  41026. blendDstAlpha = blendDstAlpha || blendDst;
  41027. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  41028. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  41029. this.currentBlendEquation = blendEquation;
  41030. this.currentBlendEquationAlpha = blendEquationAlpha;
  41031. }
  41032. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  41033. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  41034. this.currentBlendSrc = blendSrc;
  41035. this.currentBlendDst = blendDst;
  41036. this.currentBlendSrcAlpha = blendSrcAlpha;
  41037. this.currentBlendDstAlpha = blendDstAlpha;
  41038. }
  41039. this.currentBlending = blending;
  41040. this.currentPremultipledAlpha = false;
  41041. }
  41042. /**
  41043. * Specifies whether colors can be written when rendering
  41044. * into a framebuffer or not.
  41045. *
  41046. * This method caches the state so `gl.colorMask()` is only
  41047. * called when necessary.
  41048. *
  41049. * @param {boolean} colorMask - The color mask.
  41050. */
  41051. setColorMask( colorMask ) {
  41052. if ( this.currentColorMask !== colorMask ) {
  41053. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  41054. this.currentColorMask = colorMask;
  41055. }
  41056. }
  41057. /**
  41058. * Specifies whether the depth test is enabled or not.
  41059. *
  41060. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  41061. */
  41062. setDepthTest( depthTest ) {
  41063. const { gl } = this;
  41064. if ( depthTest ) {
  41065. this.enable( gl.DEPTH_TEST );
  41066. } else {
  41067. this.disable( gl.DEPTH_TEST );
  41068. }
  41069. }
  41070. /**
  41071. * Specifies whether depth values can be written when rendering
  41072. * into a framebuffer or not.
  41073. *
  41074. * This method caches the state so `gl.depthMask()` is only
  41075. * called when necessary.
  41076. *
  41077. * @param {boolean} depthMask - The depth mask.
  41078. */
  41079. setDepthMask( depthMask ) {
  41080. if ( this.currentDepthMask !== depthMask ) {
  41081. this.gl.depthMask( depthMask );
  41082. this.currentDepthMask = depthMask;
  41083. }
  41084. }
  41085. /**
  41086. * Specifies the depth compare function.
  41087. *
  41088. * This method caches the state so `gl.depthFunc()` is only
  41089. * called when necessary.
  41090. *
  41091. * @param {number} depthFunc - The depth compare function.
  41092. */
  41093. setDepthFunc( depthFunc ) {
  41094. if ( this.currentDepthFunc !== depthFunc ) {
  41095. const { gl } = this;
  41096. switch ( depthFunc ) {
  41097. case NeverDepth:
  41098. gl.depthFunc( gl.NEVER );
  41099. break;
  41100. case AlwaysDepth:
  41101. gl.depthFunc( gl.ALWAYS );
  41102. break;
  41103. case LessDepth:
  41104. gl.depthFunc( gl.LESS );
  41105. break;
  41106. case LessEqualDepth:
  41107. gl.depthFunc( gl.LEQUAL );
  41108. break;
  41109. case EqualDepth:
  41110. gl.depthFunc( gl.EQUAL );
  41111. break;
  41112. case GreaterEqualDepth:
  41113. gl.depthFunc( gl.GEQUAL );
  41114. break;
  41115. case GreaterDepth:
  41116. gl.depthFunc( gl.GREATER );
  41117. break;
  41118. case NotEqualDepth:
  41119. gl.depthFunc( gl.NOTEQUAL );
  41120. break;
  41121. default:
  41122. gl.depthFunc( gl.LEQUAL );
  41123. }
  41124. this.currentDepthFunc = depthFunc;
  41125. }
  41126. }
  41127. /**
  41128. * Specifies the scissor box.
  41129. *
  41130. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41131. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41132. * @param {number} width - The width of the viewport.
  41133. * @param {number} height - The height of the viewport.
  41134. *
  41135. */
  41136. scissor( x, y, width, height ) {
  41137. const scissor = this._tempVec4.set( x, y, width, height );
  41138. if ( this.currentScissor.equals( scissor ) === false ) {
  41139. const { gl } = this;
  41140. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  41141. this.currentScissor.copy( scissor );
  41142. }
  41143. }
  41144. /**
  41145. * Specifies the viewport.
  41146. *
  41147. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41148. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41149. * @param {number} width - The width of the viewport.
  41150. * @param {number} height - The height of the viewport.
  41151. *
  41152. */
  41153. viewport( x, y, width, height ) {
  41154. const viewport = this._tempVec4.set( x, y, width, height );
  41155. if ( this.currentViewport.equals( viewport ) === false ) {
  41156. const { gl } = this;
  41157. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  41158. this.currentViewport.copy( viewport );
  41159. }
  41160. }
  41161. /**
  41162. * Defines the scissor test.
  41163. *
  41164. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41165. */
  41166. setScissorTest( boolean ) {
  41167. const gl = this.gl;
  41168. if ( boolean ) {
  41169. gl.enable( gl.SCISSOR_TEST );
  41170. } else {
  41171. gl.disable( gl.SCISSOR_TEST );
  41172. }
  41173. }
  41174. /**
  41175. * Specifies whether the stencil test is enabled or not.
  41176. *
  41177. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  41178. */
  41179. setStencilTest( stencilTest ) {
  41180. const { gl } = this;
  41181. if ( stencilTest ) {
  41182. this.enable( gl.STENCIL_TEST );
  41183. } else {
  41184. this.disable( gl.STENCIL_TEST );
  41185. }
  41186. }
  41187. /**
  41188. * Specifies whether stencil values can be written when rendering
  41189. * into a framebuffer or not.
  41190. *
  41191. * This method caches the state so `gl.stencilMask()` is only
  41192. * called when necessary.
  41193. *
  41194. * @param {boolean} stencilMask - The stencil mask.
  41195. */
  41196. setStencilMask( stencilMask ) {
  41197. if ( this.currentStencilMask !== stencilMask ) {
  41198. this.gl.stencilMask( stencilMask );
  41199. this.currentStencilMask = stencilMask;
  41200. }
  41201. }
  41202. /**
  41203. * Specifies whether the stencil test functions.
  41204. *
  41205. * This method caches the state so `gl.stencilFunc()` is only
  41206. * called when necessary.
  41207. *
  41208. * @param {number} stencilFunc - The stencil compare function.
  41209. * @param {number} stencilRef - The reference value for the stencil test.
  41210. * @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.
  41211. */
  41212. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  41213. if ( this.currentStencilFunc !== stencilFunc ||
  41214. this.currentStencilRef !== stencilRef ||
  41215. this.currentStencilFuncMask !== stencilMask ) {
  41216. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  41217. this.currentStencilFunc = stencilFunc;
  41218. this.currentStencilRef = stencilRef;
  41219. this.currentStencilFuncMask = stencilMask;
  41220. }
  41221. }
  41222. /**
  41223. * Specifies whether the stencil test operation.
  41224. *
  41225. * This method caches the state so `gl.stencilOp()` is only
  41226. * called when necessary.
  41227. *
  41228. * @param {number} stencilFail - The function to use when the stencil test fails.
  41229. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  41230. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  41231. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  41232. */
  41233. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  41234. if ( this.currentStencilFail !== stencilFail ||
  41235. this.currentStencilZFail !== stencilZFail ||
  41236. this.currentStencilZPass !== stencilZPass ) {
  41237. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  41238. this.currentStencilFail = stencilFail;
  41239. this.currentStencilZFail = stencilZFail;
  41240. this.currentStencilZPass = stencilZPass;
  41241. }
  41242. }
  41243. /**
  41244. * Configures the WebGL state for the given material.
  41245. *
  41246. * @param {Material} material - The material to configure the state for.
  41247. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  41248. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  41249. */
  41250. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  41251. const { gl } = this;
  41252. material.side === DoubleSide
  41253. ? this.disable( gl.CULL_FACE )
  41254. : this.enable( gl.CULL_FACE );
  41255. let flipSided = ( material.side === BackSide );
  41256. if ( frontFaceCW ) flipSided = ! flipSided;
  41257. this.setFlipSided( flipSided );
  41258. ( material.blending === NormalBlending && material.transparent === false )
  41259. ? this.setBlending( NoBlending )
  41260. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  41261. this.setDepthFunc( material.depthFunc );
  41262. this.setDepthTest( material.depthTest );
  41263. this.setDepthMask( material.depthWrite );
  41264. this.setColorMask( material.colorWrite );
  41265. const stencilWrite = material.stencilWrite;
  41266. this.setStencilTest( stencilWrite );
  41267. if ( stencilWrite ) {
  41268. this.setStencilMask( material.stencilWriteMask );
  41269. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  41270. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  41271. }
  41272. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  41273. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  41274. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  41275. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  41276. if ( hardwareClippingPlanes > 0 ) {
  41277. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  41278. const CLIP_DISTANCE0_WEBGL = 0x3000;
  41279. for ( let i = 0; i < 8; i ++ ) {
  41280. if ( i < hardwareClippingPlanes ) {
  41281. this.enable( CLIP_DISTANCE0_WEBGL + i );
  41282. } else {
  41283. this.disable( CLIP_DISTANCE0_WEBGL + i );
  41284. }
  41285. }
  41286. }
  41287. }
  41288. }
  41289. /**
  41290. * Specifies the polygon offset.
  41291. *
  41292. * This method caches the state so `gl.polygonOffset()` is only
  41293. * called when necessary.
  41294. *
  41295. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  41296. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  41297. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  41298. */
  41299. setPolygonOffset( polygonOffset, factor, units ) {
  41300. const { gl } = this;
  41301. if ( polygonOffset ) {
  41302. this.enable( gl.POLYGON_OFFSET_FILL );
  41303. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  41304. gl.polygonOffset( factor, units );
  41305. this.currentPolygonOffsetFactor = factor;
  41306. this.currentPolygonOffsetUnits = units;
  41307. }
  41308. } else {
  41309. this.disable( gl.POLYGON_OFFSET_FILL );
  41310. }
  41311. }
  41312. /**
  41313. * Defines the usage of the given WebGL program.
  41314. *
  41315. * This method caches the state so `gl.useProgram()` is only
  41316. * called when necessary.
  41317. *
  41318. * @param {WebGLProgram} program - The WebGL program to use.
  41319. * @return {boolean} Whether a program change has been executed or not.
  41320. */
  41321. useProgram( program ) {
  41322. if ( this.currentProgram !== program ) {
  41323. this.gl.useProgram( program );
  41324. this.currentProgram = program;
  41325. return true;
  41326. }
  41327. return false;
  41328. }
  41329. /**
  41330. * Sets the vertex state by binding the given VAO and element buffer.
  41331. *
  41332. * @param {WebGLVertexArrayObject} vao - The VAO.
  41333. * @param {WebGLBuffer} indexBuffer - The index buffer.
  41334. * @return {boolean} Whether a vertex state has been changed or not.
  41335. */
  41336. setVertexState( vao, indexBuffer = null ) {
  41337. const gl = this.gl;
  41338. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  41339. gl.bindVertexArray( vao );
  41340. if ( indexBuffer !== null ) {
  41341. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  41342. }
  41343. this.currentVAO = vao;
  41344. this.currentIndex = indexBuffer;
  41345. return true;
  41346. }
  41347. return false;
  41348. }
  41349. /**
  41350. * Resets the vertex array state by resetting the VAO and element buffer.
  41351. */
  41352. resetVertexState() {
  41353. const gl = this.gl;
  41354. gl.bindVertexArray( null );
  41355. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  41356. this.currentVAO = null;
  41357. this.currentIndex = null;
  41358. }
  41359. // framebuffer
  41360. /**
  41361. * Binds the given framebuffer.
  41362. *
  41363. * This method caches the state so `gl.bindFramebuffer()` is only
  41364. * called when necessary.
  41365. *
  41366. * @param {number} target - The binding point (target).
  41367. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  41368. * @return {boolean} Whether a bind has been executed or not.
  41369. */
  41370. bindFramebuffer( target, framebuffer ) {
  41371. const { gl, currentBoundFramebuffers } = this;
  41372. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  41373. gl.bindFramebuffer( target, framebuffer );
  41374. currentBoundFramebuffers[ target ] = framebuffer;
  41375. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  41376. if ( target === gl.DRAW_FRAMEBUFFER ) {
  41377. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  41378. }
  41379. if ( target === gl.FRAMEBUFFER ) {
  41380. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  41381. }
  41382. return true;
  41383. }
  41384. return false;
  41385. }
  41386. /**
  41387. * Defines draw buffers to which fragment colors are written into.
  41388. * Configures the MRT setup of custom framebuffers.
  41389. *
  41390. * This method caches the state so `gl.drawBuffers()` is only
  41391. * called when necessary.
  41392. *
  41393. * @param {RenderContext} renderContext - The render context.
  41394. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  41395. */
  41396. drawBuffers( renderContext, framebuffer ) {
  41397. const { gl } = this;
  41398. let drawBuffers = [];
  41399. let needsUpdate = false;
  41400. if ( renderContext.textures !== null ) {
  41401. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  41402. if ( drawBuffers === undefined ) {
  41403. drawBuffers = [];
  41404. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  41405. }
  41406. const textures = renderContext.textures;
  41407. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  41408. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  41409. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  41410. }
  41411. drawBuffers.length = textures.length;
  41412. needsUpdate = true;
  41413. }
  41414. } else {
  41415. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  41416. drawBuffers[ 0 ] = gl.BACK;
  41417. needsUpdate = true;
  41418. }
  41419. }
  41420. if ( needsUpdate ) {
  41421. gl.drawBuffers( drawBuffers );
  41422. }
  41423. }
  41424. // texture
  41425. /**
  41426. * Makes the given texture unit active.
  41427. *
  41428. * This method caches the state so `gl.activeTexture()` is only
  41429. * called when necessary.
  41430. *
  41431. * @param {number} webglSlot - The texture unit to make active.
  41432. */
  41433. activeTexture( webglSlot ) {
  41434. const { gl, currentTextureSlot, maxTextures } = this;
  41435. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41436. if ( currentTextureSlot !== webglSlot ) {
  41437. gl.activeTexture( webglSlot );
  41438. this.currentTextureSlot = webglSlot;
  41439. }
  41440. }
  41441. /**
  41442. * Binds the given WebGL texture to a target.
  41443. *
  41444. * This method caches the state so `gl.bindTexture()` is only
  41445. * called when necessary.
  41446. *
  41447. * @param {number} webglType - The binding point (target).
  41448. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  41449. * @param {number} webglSlot - The texture.
  41450. */
  41451. bindTexture( webglType, webglTexture, webglSlot ) {
  41452. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  41453. if ( webglSlot === undefined ) {
  41454. if ( currentTextureSlot === null ) {
  41455. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41456. } else {
  41457. webglSlot = currentTextureSlot;
  41458. }
  41459. }
  41460. let boundTexture = currentBoundTextures[ webglSlot ];
  41461. if ( boundTexture === undefined ) {
  41462. boundTexture = { type: undefined, texture: undefined };
  41463. currentBoundTextures[ webglSlot ] = boundTexture;
  41464. }
  41465. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  41466. if ( currentTextureSlot !== webglSlot ) {
  41467. gl.activeTexture( webglSlot );
  41468. this.currentTextureSlot = webglSlot;
  41469. }
  41470. gl.bindTexture( webglType, webglTexture );
  41471. boundTexture.type = webglType;
  41472. boundTexture.texture = webglTexture;
  41473. }
  41474. }
  41475. /**
  41476. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  41477. *
  41478. * This method caches the state so `gl.bindBufferBase()` is only
  41479. * called when necessary.
  41480. *
  41481. * @param {number} target - The target for the bind operation.
  41482. * @param {number} index - The index of the target.
  41483. * @param {WebGLBuffer} buffer - The WebGL buffer.
  41484. * @return {boolean} Whether a bind has been executed or not.
  41485. */
  41486. bindBufferBase( target, index, buffer ) {
  41487. const { gl } = this;
  41488. const key = `${target}-${index}`;
  41489. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  41490. gl.bindBufferBase( target, index, buffer );
  41491. this.currentBoundBufferBases[ key ] = buffer;
  41492. return true;
  41493. }
  41494. return false;
  41495. }
  41496. /**
  41497. * Unbinds the current bound texture.
  41498. *
  41499. * This method caches the state so `gl.bindTexture()` is only
  41500. * called when necessary.
  41501. */
  41502. unbindTexture() {
  41503. const { gl, currentTextureSlot, currentBoundTextures } = this;
  41504. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  41505. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  41506. gl.bindTexture( boundTexture.type, null );
  41507. boundTexture.type = undefined;
  41508. boundTexture.texture = undefined;
  41509. }
  41510. }
  41511. }
  41512. /**
  41513. * A WebGL 2 backend utility module with common helpers.
  41514. *
  41515. * @private
  41516. */
  41517. class WebGLUtils {
  41518. /**
  41519. * Constructs a new utility object.
  41520. *
  41521. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41522. */
  41523. constructor( backend ) {
  41524. /**
  41525. * A reference to the WebGL 2 backend.
  41526. *
  41527. * @type {WebGLBackend}
  41528. */
  41529. this.backend = backend;
  41530. /**
  41531. * A reference to the rendering context.
  41532. *
  41533. * @type {WebGL2RenderingContext}
  41534. */
  41535. this.gl = this.backend.gl;
  41536. /**
  41537. * A reference to a backend module holding extension-related
  41538. * utility functions.
  41539. *
  41540. * @type {WebGLExtensions}
  41541. */
  41542. this.extensions = backend.extensions;
  41543. }
  41544. /**
  41545. * Converts the given three.js constant into a WebGL constant.
  41546. * The method currently supports the conversion of texture formats
  41547. * and types.
  41548. *
  41549. * @param {number} p - The three.js constant.
  41550. * @param {string} [colorSpace=NoColorSpace] - The color space.
  41551. * @return {?number} The corresponding WebGL constant.
  41552. */
  41553. convert( p, colorSpace = NoColorSpace ) {
  41554. const { gl, extensions } = this;
  41555. let extension;
  41556. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  41557. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  41558. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  41559. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  41560. if ( p === ByteType ) return gl.BYTE;
  41561. if ( p === ShortType ) return gl.SHORT;
  41562. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  41563. if ( p === IntType ) return gl.INT;
  41564. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  41565. if ( p === FloatType ) return gl.FLOAT;
  41566. if ( p === HalfFloatType ) {
  41567. return gl.HALF_FLOAT;
  41568. }
  41569. if ( p === AlphaFormat ) return gl.ALPHA;
  41570. if ( p === RGBFormat ) return gl.RGB;
  41571. if ( p === RGBAFormat ) return gl.RGBA;
  41572. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  41573. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  41574. // WebGL2 formats.
  41575. if ( p === RedFormat ) return gl.RED;
  41576. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  41577. if ( p === RGFormat ) return gl.RG;
  41578. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  41579. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  41580. // S3TC
  41581. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  41582. if ( colorSpace === SRGBColorSpace ) {
  41583. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  41584. if ( extension !== null ) {
  41585. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  41586. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  41587. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  41588. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  41589. } else {
  41590. return null;
  41591. }
  41592. } else {
  41593. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  41594. if ( extension !== null ) {
  41595. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  41596. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41597. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41598. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41599. } else {
  41600. return null;
  41601. }
  41602. }
  41603. }
  41604. // PVRTC
  41605. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  41606. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  41607. if ( extension !== null ) {
  41608. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  41609. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  41610. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  41611. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  41612. } else {
  41613. return null;
  41614. }
  41615. }
  41616. // ETC
  41617. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  41618. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  41619. if ( extension !== null ) {
  41620. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  41621. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  41622. } else {
  41623. return null;
  41624. }
  41625. }
  41626. // ASTC
  41627. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  41628. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  41629. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  41630. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  41631. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  41632. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  41633. if ( extension !== null ) {
  41634. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  41635. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  41636. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  41637. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  41638. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  41639. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  41640. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  41641. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  41642. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  41643. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  41644. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  41645. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  41646. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  41647. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  41648. } else {
  41649. return null;
  41650. }
  41651. }
  41652. // BPTC
  41653. if ( p === RGBA_BPTC_Format ) {
  41654. extension = extensions.get( 'EXT_texture_compression_bptc' );
  41655. if ( extension !== null ) {
  41656. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  41657. } else {
  41658. return null;
  41659. }
  41660. }
  41661. // RGTC
  41662. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  41663. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  41664. if ( extension !== null ) {
  41665. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  41666. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  41667. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  41668. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  41669. } else {
  41670. return null;
  41671. }
  41672. }
  41673. //
  41674. if ( p === UnsignedInt248Type ) {
  41675. return gl.UNSIGNED_INT_24_8;
  41676. }
  41677. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  41678. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  41679. }
  41680. /**
  41681. * This method can be used to synchronize the CPU with the GPU by waiting until
  41682. * ongoing GPU commands have been completed.
  41683. *
  41684. * @private
  41685. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  41686. */
  41687. _clientWaitAsync() {
  41688. const { gl } = this;
  41689. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  41690. gl.flush();
  41691. return new Promise( ( resolve, reject ) => {
  41692. function test() {
  41693. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  41694. if ( res === gl.WAIT_FAILED ) {
  41695. gl.deleteSync( sync );
  41696. reject();
  41697. return;
  41698. }
  41699. if ( res === gl.TIMEOUT_EXPIRED ) {
  41700. requestAnimationFrame( test );
  41701. return;
  41702. }
  41703. gl.deleteSync( sync );
  41704. resolve();
  41705. }
  41706. test();
  41707. } );
  41708. }
  41709. }
  41710. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  41711. /**
  41712. * A WebGL 2 backend utility module for managing textures.
  41713. *
  41714. * @private
  41715. */
  41716. class WebGLTextureUtils {
  41717. /**
  41718. * Constructs a new utility object.
  41719. *
  41720. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41721. */
  41722. constructor( backend ) {
  41723. /**
  41724. * A reference to the WebGL 2 backend.
  41725. *
  41726. * @type {WebGLBackend}
  41727. */
  41728. this.backend = backend;
  41729. /**
  41730. * A reference to the rendering context.
  41731. *
  41732. * @type {WebGL2RenderingContext}
  41733. */
  41734. this.gl = backend.gl;
  41735. /**
  41736. * A reference to a backend module holding extension-related
  41737. * utility functions.
  41738. *
  41739. * @type {WebGLExtensions}
  41740. */
  41741. this.extensions = backend.extensions;
  41742. /**
  41743. * A dictionary for managing default textures. The key
  41744. * is the binding point (target), the value the WEbGL texture object.
  41745. *
  41746. * @type {Object<GLenum,WebGLTexture>}
  41747. */
  41748. this.defaultTextures = {};
  41749. if ( initialized === false ) {
  41750. this._init();
  41751. initialized = true;
  41752. }
  41753. }
  41754. /**
  41755. * Inits the state of the utility.
  41756. *
  41757. * @private
  41758. */
  41759. _init() {
  41760. const gl = this.gl;
  41761. // Store only WebGL constants here.
  41762. wrappingToGL = {
  41763. [ RepeatWrapping ]: gl.REPEAT,
  41764. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  41765. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  41766. };
  41767. filterToGL = {
  41768. [ NearestFilter ]: gl.NEAREST,
  41769. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  41770. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  41771. [ LinearFilter ]: gl.LINEAR,
  41772. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  41773. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  41774. };
  41775. compareToGL = {
  41776. [ NeverCompare ]: gl.NEVER,
  41777. [ AlwaysCompare ]: gl.ALWAYS,
  41778. [ LessCompare ]: gl.LESS,
  41779. [ LessEqualCompare ]: gl.LEQUAL,
  41780. [ EqualCompare ]: gl.EQUAL,
  41781. [ GreaterEqualCompare ]: gl.GEQUAL,
  41782. [ GreaterCompare ]: gl.GREATER,
  41783. [ NotEqualCompare ]: gl.NOTEQUAL
  41784. };
  41785. }
  41786. /**
  41787. * Returns the native texture type for the given texture.
  41788. *
  41789. * @param {Texture} texture - The texture.
  41790. * @return {GLenum} The native texture type.
  41791. */
  41792. getGLTextureType( texture ) {
  41793. const { gl } = this;
  41794. let glTextureType;
  41795. if ( texture.isCubeTexture === true ) {
  41796. glTextureType = gl.TEXTURE_CUBE_MAP;
  41797. } else if ( texture.isDepthArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true || texture.isTextureArray === true ) {
  41798. glTextureType = gl.TEXTURE_2D_ARRAY;
  41799. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  41800. glTextureType = gl.TEXTURE_3D;
  41801. } else {
  41802. glTextureType = gl.TEXTURE_2D;
  41803. }
  41804. return glTextureType;
  41805. }
  41806. /**
  41807. * Returns the native texture type for the given texture.
  41808. *
  41809. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  41810. * @param {GLenum} glFormat - The WebGL format.
  41811. * @param {GLenum} glType - The WebGL type.
  41812. * @param {string} colorSpace - The texture's color space.
  41813. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  41814. * @return {GLenum} The internal format.
  41815. */
  41816. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  41817. const { gl, extensions } = this;
  41818. if ( internalFormatName !== null ) {
  41819. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  41820. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  41821. }
  41822. let internalFormat = glFormat;
  41823. if ( glFormat === gl.RED ) {
  41824. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  41825. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  41826. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  41827. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  41828. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  41829. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  41830. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  41831. if ( glType === gl.INT ) internalFormat = gl.R32I;
  41832. }
  41833. if ( glFormat === gl.RED_INTEGER ) {
  41834. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  41835. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  41836. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  41837. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  41838. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  41839. if ( glType === gl.INT ) internalFormat = gl.R32I;
  41840. }
  41841. if ( glFormat === gl.RG ) {
  41842. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  41843. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  41844. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  41845. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  41846. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  41847. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  41848. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  41849. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  41850. }
  41851. if ( glFormat === gl.RG_INTEGER ) {
  41852. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  41853. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  41854. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  41855. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  41856. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  41857. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  41858. }
  41859. if ( glFormat === gl.RGB ) {
  41860. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  41861. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  41862. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  41863. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  41864. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  41865. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  41866. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  41867. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  41868. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  41869. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  41870. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  41871. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  41872. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  41873. }
  41874. if ( glFormat === gl.RGB_INTEGER ) {
  41875. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  41876. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  41877. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  41878. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  41879. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  41880. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  41881. }
  41882. if ( glFormat === gl.RGBA ) {
  41883. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  41884. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  41885. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  41886. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  41887. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  41888. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  41889. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  41890. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  41891. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  41892. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  41893. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  41894. }
  41895. if ( glFormat === gl.RGBA_INTEGER ) {
  41896. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  41897. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  41898. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  41899. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  41900. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  41901. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  41902. }
  41903. if ( glFormat === gl.DEPTH_COMPONENT ) {
  41904. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  41905. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  41906. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  41907. }
  41908. if ( glFormat === gl.DEPTH_STENCIL ) {
  41909. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  41910. }
  41911. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  41912. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  41913. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  41914. extensions.get( 'EXT_color_buffer_float' );
  41915. }
  41916. return internalFormat;
  41917. }
  41918. /**
  41919. * Sets the texture parameters for the given texture.
  41920. *
  41921. * @param {GLenum} textureType - The texture type.
  41922. * @param {Texture} texture - The texture.
  41923. */
  41924. setTextureParameters( textureType, texture ) {
  41925. const { gl, extensions, backend } = this;
  41926. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  41927. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  41928. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  41929. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  41930. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  41931. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  41932. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  41933. // WebGL 2 does not support wrapping for depth 2D array textures
  41934. if ( texture.isDepthArrayTexture !== true && texture.isTextureArray === false ) {
  41935. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  41936. }
  41937. }
  41938. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  41939. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  41940. // follow WebGPU backend mapping for texture filtering
  41941. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  41942. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  41943. if ( texture.compareFunction ) {
  41944. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  41945. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  41946. }
  41947. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  41948. if ( texture.magFilter === NearestFilter ) return;
  41949. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  41950. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  41951. if ( texture.anisotropy > 1 ) {
  41952. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  41953. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  41954. }
  41955. }
  41956. }
  41957. /**
  41958. * Creates a default texture for the given texture that can be used
  41959. * as a placeholder until the actual texture is ready for usage.
  41960. *
  41961. * @param {Texture} texture - The texture to create a default texture for.
  41962. */
  41963. createDefaultTexture( texture ) {
  41964. const { gl, backend, defaultTextures } = this;
  41965. const glTextureType = this.getGLTextureType( texture );
  41966. let textureGPU = defaultTextures[ glTextureType ];
  41967. if ( textureGPU === undefined ) {
  41968. textureGPU = gl.createTexture();
  41969. backend.state.bindTexture( glTextureType, textureGPU );
  41970. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  41971. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  41972. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  41973. defaultTextures[ glTextureType ] = textureGPU;
  41974. }
  41975. backend.set( texture, {
  41976. textureGPU,
  41977. glTextureType,
  41978. isDefault: true
  41979. } );
  41980. }
  41981. /**
  41982. * Defines a texture on the GPU for the given texture object.
  41983. *
  41984. * @param {Texture} texture - The texture.
  41985. * @param {Object} [options={}] - Optional configuration parameter.
  41986. * @return {undefined}
  41987. */
  41988. createTexture( texture, options ) {
  41989. const { gl, backend } = this;
  41990. const { levels, width, height, depth } = options;
  41991. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  41992. const glType = backend.utils.convert( texture.type );
  41993. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  41994. const textureGPU = gl.createTexture();
  41995. const glTextureType = this.getGLTextureType( texture );
  41996. backend.state.bindTexture( glTextureType, textureGPU );
  41997. this.setTextureParameters( glTextureType, texture );
  41998. if ( texture.isDepthArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture || texture.isTextureArray ) {
  41999. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  42000. } else if ( texture.isData3DTexture ) {
  42001. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  42002. } else if ( ! texture.isVideoTexture ) {
  42003. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  42004. }
  42005. backend.set( texture, {
  42006. textureGPU,
  42007. glTextureType,
  42008. glFormat,
  42009. glType,
  42010. glInternalFormat
  42011. } );
  42012. }
  42013. /**
  42014. * Uploads texture buffer data to the GPU memory.
  42015. *
  42016. * @param {WebGLBuffer} buffer - The buffer data.
  42017. * @param {Texture} texture - The texture,
  42018. */
  42019. copyBufferToTexture( buffer, texture ) {
  42020. const { gl, backend } = this;
  42021. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  42022. const { width, height } = texture.source.data;
  42023. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  42024. backend.state.bindTexture( glTextureType, textureGPU );
  42025. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  42026. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  42027. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  42028. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  42029. backend.state.unbindTexture();
  42030. // debug
  42031. // const framebuffer = gl.createFramebuffer();
  42032. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  42033. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  42034. // const readout = new Float32Array( width * height * 4 );
  42035. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  42036. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  42037. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  42038. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  42039. // console.log( readout );
  42040. }
  42041. /**
  42042. * Uploads the updated texture data to the GPU.
  42043. *
  42044. * @param {Texture} texture - The texture.
  42045. * @param {Object} [options={}] - Optional configuration parameter.
  42046. */
  42047. updateTexture( texture, options ) {
  42048. const { gl } = this;
  42049. const { width, height } = options;
  42050. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  42051. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  42052. return;
  42053. const getImage = ( source ) => {
  42054. if ( source.isDataTexture ) {
  42055. return source.image.data;
  42056. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  42057. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  42058. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  42059. source instanceof OffscreenCanvas ) {
  42060. return source;
  42061. }
  42062. return source.data;
  42063. };
  42064. this.backend.state.bindTexture( glTextureType, textureGPU );
  42065. this.setTextureParameters( glTextureType, texture );
  42066. if ( texture.isCompressedTexture ) {
  42067. const mipmaps = texture.mipmaps;
  42068. const image = options.image;
  42069. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42070. const mipmap = mipmaps[ i ];
  42071. if ( texture.isCompressedArrayTexture ) {
  42072. if ( texture.format !== gl.RGBA ) {
  42073. if ( glFormat !== null ) {
  42074. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  42075. } else {
  42076. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  42077. }
  42078. } else {
  42079. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  42080. }
  42081. } else {
  42082. if ( glFormat !== null ) {
  42083. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  42084. } else {
  42085. console.warn( 'Unsupported compressed texture format' );
  42086. }
  42087. }
  42088. }
  42089. } else if ( texture.isCubeTexture ) {
  42090. const images = options.images;
  42091. for ( let i = 0; i < 6; i ++ ) {
  42092. const image = getImage( images[ i ] );
  42093. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  42094. }
  42095. } else if ( texture.isDataArrayTexture || texture.isDepthArrayTexture ) {
  42096. const image = options.image;
  42097. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42098. } else if ( texture.isData3DTexture ) {
  42099. const image = options.image;
  42100. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42101. } else if ( texture.isVideoTexture ) {
  42102. texture.update();
  42103. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  42104. } else {
  42105. const image = getImage( options.image );
  42106. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  42107. }
  42108. }
  42109. /**
  42110. * Generates mipmaps for the given texture.
  42111. *
  42112. * @param {Texture} texture - The texture.
  42113. */
  42114. generateMipmaps( texture ) {
  42115. const { gl, backend } = this;
  42116. const { textureGPU, glTextureType } = backend.get( texture );
  42117. backend.state.bindTexture( glTextureType, textureGPU );
  42118. gl.generateMipmap( glTextureType );
  42119. }
  42120. /**
  42121. * Deallocates the render buffers of the given render target.
  42122. *
  42123. * @param {RenderTarget} renderTarget - The render target.
  42124. */
  42125. deallocateRenderBuffers( renderTarget ) {
  42126. const { gl, backend } = this;
  42127. // remove framebuffer reference
  42128. if ( renderTarget ) {
  42129. const renderContextData = backend.get( renderTarget );
  42130. renderContextData.renderBufferStorageSetup = undefined;
  42131. if ( renderContextData.framebuffers ) {
  42132. for ( const cacheKey in renderContextData.framebuffers ) {
  42133. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  42134. }
  42135. delete renderContextData.framebuffers;
  42136. }
  42137. if ( renderContextData.depthRenderbuffer ) {
  42138. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  42139. delete renderContextData.depthRenderbuffer;
  42140. }
  42141. if ( renderContextData.stencilRenderbuffer ) {
  42142. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  42143. delete renderContextData.stencilRenderbuffer;
  42144. }
  42145. if ( renderContextData.msaaFrameBuffer ) {
  42146. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  42147. delete renderContextData.msaaFrameBuffer;
  42148. }
  42149. if ( renderContextData.msaaRenderbuffers ) {
  42150. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  42151. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  42152. }
  42153. delete renderContextData.msaaRenderbuffers;
  42154. }
  42155. }
  42156. }
  42157. /**
  42158. * Destroys the GPU data for the given texture object.
  42159. *
  42160. * @param {Texture} texture - The texture.
  42161. */
  42162. destroyTexture( texture ) {
  42163. const { gl, backend } = this;
  42164. const { textureGPU, renderTarget } = backend.get( texture );
  42165. this.deallocateRenderBuffers( renderTarget );
  42166. gl.deleteTexture( textureGPU );
  42167. backend.delete( texture );
  42168. }
  42169. /**
  42170. * Copies data of the given source texture to the given destination texture.
  42171. *
  42172. * @param {Texture} srcTexture - The source texture.
  42173. * @param {Texture} dstTexture - The destination texture.
  42174. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42175. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42176. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42177. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42178. */
  42179. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42180. const { gl, backend } = this;
  42181. const { state } = this.backend;
  42182. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  42183. state.bindTexture( glTextureType, dstTextureGPU );
  42184. // gather the necessary dimensions to copy
  42185. let width, height, depth, minX, minY, minZ;
  42186. let dstX, dstY, dstZ;
  42187. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  42188. if ( srcRegion !== null ) {
  42189. width = srcRegion.max.x - srcRegion.min.x;
  42190. height = srcRegion.max.y - srcRegion.min.y;
  42191. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  42192. minX = srcRegion.min.x;
  42193. minY = srcRegion.min.y;
  42194. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  42195. } else {
  42196. const levelScale = Math.pow( 2, - srcLevel );
  42197. width = Math.floor( image.width * levelScale );
  42198. height = Math.floor( image.height * levelScale );
  42199. if ( srcTexture.isDataArrayTexture || srcTexture.isDepthArrayTexture ) {
  42200. depth = image.depth;
  42201. } else if ( srcTexture.isData3DTexture ) {
  42202. depth = Math.floor( image.depth * levelScale );
  42203. } else {
  42204. depth = 1;
  42205. }
  42206. minX = 0;
  42207. minY = 0;
  42208. minZ = 0;
  42209. }
  42210. if ( dstPosition !== null ) {
  42211. dstX = dstPosition.x;
  42212. dstY = dstPosition.y;
  42213. dstZ = dstPosition.z;
  42214. } else {
  42215. dstX = 0;
  42216. dstY = 0;
  42217. dstZ = 0;
  42218. }
  42219. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  42220. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  42221. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  42222. // used for copying data from cpu
  42223. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  42224. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  42225. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  42226. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  42227. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  42228. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  42229. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  42230. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  42231. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  42232. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  42233. // set up the src texture
  42234. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isDepthArrayTexture;
  42235. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  42236. const srcTextureData = backend.get( srcTexture );
  42237. const dstTextureData = backend.get( dstTexture );
  42238. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  42239. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  42240. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  42241. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  42242. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  42243. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  42244. let mask = gl.COLOR_BUFFER_BIT;
  42245. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  42246. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  42247. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  42248. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  42249. } else {
  42250. if ( isDst3D ) {
  42251. // copy data into the 3d texture
  42252. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  42253. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  42254. } else if ( dstTexture.isCompressedArrayTexture ) {
  42255. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  42256. } else {
  42257. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  42258. }
  42259. } else {
  42260. // copy data into the 2d texture
  42261. if ( srcTexture.isDataTexture ) {
  42262. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  42263. } else if ( srcTexture.isCompressedTexture ) {
  42264. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  42265. } else {
  42266. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  42267. }
  42268. }
  42269. }
  42270. // reset values
  42271. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  42272. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  42273. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  42274. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  42275. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  42276. // Generate mipmaps only when copying level 0
  42277. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  42278. gl.generateMipmap( glTextureType );
  42279. }
  42280. state.unbindTexture();
  42281. }
  42282. /**
  42283. * Copies the current bound framebuffer to the given texture.
  42284. *
  42285. * @param {Texture} texture - The destination texture.
  42286. * @param {RenderContext} renderContext - The render context.
  42287. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42288. */
  42289. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42290. const { gl } = this;
  42291. const { state } = this.backend;
  42292. const { textureGPU } = this.backend.get( texture );
  42293. const { x, y, z: width, w: height } = rectangle;
  42294. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  42295. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  42296. if ( requireDrawFrameBuffer ) {
  42297. const partial = ( x !== 0 || y !== 0 );
  42298. let mask;
  42299. let attachment;
  42300. if ( texture.isDepthTexture === true ) {
  42301. mask = gl.DEPTH_BUFFER_BIT;
  42302. attachment = gl.DEPTH_ATTACHMENT;
  42303. if ( renderContext.stencil ) {
  42304. mask |= gl.STENCIL_BUFFER_BIT;
  42305. }
  42306. } else {
  42307. mask = gl.COLOR_BUFFER_BIT;
  42308. attachment = gl.COLOR_ATTACHMENT0;
  42309. }
  42310. if ( partial ) {
  42311. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  42312. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  42313. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42314. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42315. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  42316. const flippedY = srcHeight - y - height;
  42317. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  42318. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42319. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42320. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  42321. state.unbindTexture();
  42322. } else {
  42323. const fb = gl.createFramebuffer();
  42324. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42325. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  42326. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  42327. gl.deleteFramebuffer( fb );
  42328. }
  42329. } else {
  42330. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42331. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  42332. state.unbindTexture();
  42333. }
  42334. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  42335. this.backend._setFramebuffer( renderContext );
  42336. }
  42337. /**
  42338. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  42339. *
  42340. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  42341. * @param {RenderContext} renderContext - The render context.
  42342. * @param {number} samples - The MSAA sample count.
  42343. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  42344. */
  42345. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  42346. const { gl } = this;
  42347. const renderTarget = renderContext.renderTarget;
  42348. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  42349. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  42350. if ( depthBuffer && ! stencilBuffer ) {
  42351. let glInternalFormat = gl.DEPTH_COMPONENT24;
  42352. if ( useMultisampledRTT === true ) {
  42353. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42354. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  42355. } else if ( samples > 0 ) {
  42356. if ( depthTexture && depthTexture.isDepthTexture ) {
  42357. if ( depthTexture.type === gl.FLOAT ) {
  42358. glInternalFormat = gl.DEPTH_COMPONENT32F;
  42359. }
  42360. }
  42361. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  42362. } else {
  42363. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  42364. }
  42365. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42366. } else if ( depthBuffer && stencilBuffer ) {
  42367. if ( samples > 0 ) {
  42368. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  42369. } else {
  42370. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  42371. }
  42372. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42373. }
  42374. }
  42375. /**
  42376. * Returns texture data as a typed array.
  42377. *
  42378. * @async
  42379. * @param {Texture} texture - The texture to copy.
  42380. * @param {number} x - The x coordinate of the copy origin.
  42381. * @param {number} y - The y coordinate of the copy origin.
  42382. * @param {number} width - The width of the copy.
  42383. * @param {number} height - The height of the copy.
  42384. * @param {number} faceIndex - The face index.
  42385. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42386. */
  42387. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42388. const { backend, gl } = this;
  42389. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  42390. const fb = gl.createFramebuffer();
  42391. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42392. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  42393. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  42394. const typedArrayType = this._getTypedArrayType( glType );
  42395. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  42396. const elementCount = width * height;
  42397. const byteLength = elementCount * bytesPerTexel;
  42398. const buffer = gl.createBuffer();
  42399. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42400. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  42401. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  42402. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42403. await backend.utils._clientWaitAsync();
  42404. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  42405. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42406. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  42407. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42408. gl.deleteFramebuffer( fb );
  42409. return dstBuffer;
  42410. }
  42411. /**
  42412. * Returns the corresponding typed array type for the given WebGL data type.
  42413. *
  42414. * @private
  42415. * @param {GLenum} glType - The WebGL data type.
  42416. * @return {TypedArray.constructor} The typed array type.
  42417. */
  42418. _getTypedArrayType( glType ) {
  42419. const { gl } = this;
  42420. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  42421. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  42422. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  42423. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  42424. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  42425. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  42426. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  42427. if ( glType === gl.FLOAT ) return Float32Array;
  42428. throw new Error( `Unsupported WebGL type: ${glType}` );
  42429. }
  42430. /**
  42431. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  42432. *
  42433. * @private
  42434. * @param {GLenum} glType - The WebGL data type.
  42435. * @param {GLenum} glFormat - The WebGL texture format.
  42436. * @return {number} The bytes-per-texel.
  42437. */
  42438. _getBytesPerTexel( glType, glFormat ) {
  42439. const { gl } = this;
  42440. let bytesPerComponent = 0;
  42441. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  42442. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  42443. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  42444. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  42445. glType === gl.UNSIGNED_SHORT ||
  42446. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  42447. if ( glType === gl.UNSIGNED_INT ||
  42448. glType === gl.FLOAT ) bytesPerComponent = 4;
  42449. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  42450. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  42451. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  42452. }
  42453. }
  42454. /**
  42455. * A WebGL 2 backend utility module for managing extensions.
  42456. *
  42457. * @private
  42458. */
  42459. class WebGLExtensions {
  42460. /**
  42461. * Constructs a new utility object.
  42462. *
  42463. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42464. */
  42465. constructor( backend ) {
  42466. /**
  42467. * A reference to the WebGL 2 backend.
  42468. *
  42469. * @type {WebGLBackend}
  42470. */
  42471. this.backend = backend;
  42472. /**
  42473. * A reference to the rendering context.
  42474. *
  42475. * @type {WebGL2RenderingContext}
  42476. */
  42477. this.gl = this.backend.gl;
  42478. /**
  42479. * A list with all the supported WebGL extensions.
  42480. *
  42481. * @type {Array<string>}
  42482. */
  42483. this.availableExtensions = this.gl.getSupportedExtensions();
  42484. /**
  42485. * A dictionary with requested WebGL extensions.
  42486. * The key is the name of the extension, the value
  42487. * the requested extension object.
  42488. *
  42489. * @type {Object<string,Object>}
  42490. */
  42491. this.extensions = {};
  42492. }
  42493. /**
  42494. * Returns the extension object for the given extension name.
  42495. *
  42496. * @param {string} name - The extension name.
  42497. * @return {Object} The extension object.
  42498. */
  42499. get( name ) {
  42500. let extension = this.extensions[ name ];
  42501. if ( extension === undefined ) {
  42502. extension = this.gl.getExtension( name );
  42503. this.extensions[ name ] = extension;
  42504. }
  42505. return extension;
  42506. }
  42507. /**
  42508. * Returns `true` if the requested extension is available.
  42509. *
  42510. * @param {string} name - The extension name.
  42511. * @return {boolean} Whether the given extension is available or not.
  42512. */
  42513. has( name ) {
  42514. return this.availableExtensions.includes( name );
  42515. }
  42516. }
  42517. /**
  42518. * A WebGL 2 backend utility module for managing the device's capabilities.
  42519. *
  42520. * @private
  42521. */
  42522. class WebGLCapabilities {
  42523. /**
  42524. * Constructs a new utility object.
  42525. *
  42526. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42527. */
  42528. constructor( backend ) {
  42529. /**
  42530. * A reference to the WebGL 2 backend.
  42531. *
  42532. * @type {WebGLBackend}
  42533. */
  42534. this.backend = backend;
  42535. /**
  42536. * This value holds the cached max anisotropy value.
  42537. *
  42538. * @type {?number}
  42539. * @default null
  42540. */
  42541. this.maxAnisotropy = null;
  42542. }
  42543. /**
  42544. * Returns the maximum anisotropy texture filtering value. This value
  42545. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  42546. * WebGL extension.
  42547. *
  42548. * @return {number} The maximum anisotropy texture filtering value.
  42549. */
  42550. getMaxAnisotropy() {
  42551. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  42552. const gl = this.backend.gl;
  42553. const extensions = this.backend.extensions;
  42554. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  42555. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  42556. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  42557. } else {
  42558. this.maxAnisotropy = 0;
  42559. }
  42560. return this.maxAnisotropy;
  42561. }
  42562. }
  42563. const GLFeatureName = {
  42564. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  42565. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  42566. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  42567. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  42568. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  42569. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  42570. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  42571. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  42572. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  42573. 'OVR_multiview2': 'OVR_multiview2'
  42574. };
  42575. class WebGLBufferRenderer {
  42576. constructor( backend ) {
  42577. this.gl = backend.gl;
  42578. this.extensions = backend.extensions;
  42579. this.info = backend.renderer.info;
  42580. this.mode = null;
  42581. this.index = 0;
  42582. this.type = null;
  42583. this.object = null;
  42584. }
  42585. render( start, count ) {
  42586. const { gl, mode, object, type, info, index } = this;
  42587. if ( index !== 0 ) {
  42588. gl.drawElements( mode, count, type, start );
  42589. } else {
  42590. gl.drawArrays( mode, start, count );
  42591. }
  42592. info.update( object, count, 1 );
  42593. }
  42594. renderInstances( start, count, primcount ) {
  42595. const { gl, mode, type, index, object, info } = this;
  42596. if ( primcount === 0 ) return;
  42597. if ( index !== 0 ) {
  42598. gl.drawElementsInstanced( mode, count, type, start, primcount );
  42599. } else {
  42600. gl.drawArraysInstanced( mode, start, count, primcount );
  42601. }
  42602. info.update( object, count, primcount );
  42603. }
  42604. renderMultiDraw( starts, counts, drawCount ) {
  42605. const { extensions, mode, object, info } = this;
  42606. if ( drawCount === 0 ) return;
  42607. const extension = extensions.get( 'WEBGL_multi_draw' );
  42608. if ( extension === null ) {
  42609. for ( let i = 0; i < drawCount; i ++ ) {
  42610. this.render( starts[ i ], counts[ i ] );
  42611. }
  42612. } else {
  42613. if ( this.index !== 0 ) {
  42614. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  42615. } else {
  42616. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  42617. }
  42618. let elementCount = 0;
  42619. for ( let i = 0; i < drawCount; i ++ ) {
  42620. elementCount += counts[ i ];
  42621. }
  42622. info.update( object, elementCount, 1 );
  42623. }
  42624. }
  42625. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  42626. const { extensions, mode, object, info } = this;
  42627. if ( drawCount === 0 ) return;
  42628. const extension = extensions.get( 'WEBGL_multi_draw' );
  42629. if ( extension === null ) {
  42630. for ( let i = 0; i < drawCount; i ++ ) {
  42631. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  42632. }
  42633. } else {
  42634. if ( this.index !== 0 ) {
  42635. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  42636. } else {
  42637. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  42638. }
  42639. let elementCount = 0;
  42640. for ( let i = 0; i < drawCount; i ++ ) {
  42641. elementCount += counts[ i ] * primcount[ i ];
  42642. }
  42643. info.update( object, elementCount, 1 );
  42644. }
  42645. }
  42646. //
  42647. }
  42648. /**
  42649. * Abstract base class of a timestamp query pool.
  42650. *
  42651. * @abstract
  42652. */
  42653. class TimestampQueryPool {
  42654. /**
  42655. * Creates a new timestamp query pool.
  42656. *
  42657. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  42658. */
  42659. constructor( maxQueries = 256 ) {
  42660. /**
  42661. * Whether to track timestamps or not.
  42662. *
  42663. * @type {boolean}
  42664. * @default true
  42665. */
  42666. this.trackTimestamp = true;
  42667. /**
  42668. * Maximum number of queries this pool can hold.
  42669. *
  42670. * @type {number}
  42671. * @default 256
  42672. */
  42673. this.maxQueries = maxQueries;
  42674. /**
  42675. * How many queries allocated so far.
  42676. *
  42677. * @type {number}
  42678. * @default 0
  42679. */
  42680. this.currentQueryIndex = 0;
  42681. /**
  42682. * Tracks offsets for different contexts.
  42683. *
  42684. * @type {Map<string, number>}
  42685. */
  42686. this.queryOffsets = new Map();
  42687. /**
  42688. * Whether the pool has been disposed or not.
  42689. *
  42690. * @type {boolean}
  42691. * @default false
  42692. */
  42693. this.isDisposed = false;
  42694. /**
  42695. * TODO
  42696. *
  42697. * @type {number}
  42698. * @default 0
  42699. */
  42700. this.lastValue = 0;
  42701. /**
  42702. * TODO
  42703. *
  42704. * @type {boolean}
  42705. * @default false
  42706. */
  42707. this.pendingResolve = false;
  42708. }
  42709. /**
  42710. * Allocate queries for a specific renderContext.
  42711. *
  42712. * @abstract
  42713. * @param {Object} renderContext - The render context to allocate queries for.
  42714. * @returns {?number}
  42715. */
  42716. allocateQueriesForContext( /* renderContext */ ) {}
  42717. /**
  42718. * Resolve all timestamps and return data (or process them).
  42719. *
  42720. * @abstract
  42721. * @async
  42722. * @returns {Promise<number>|number} The resolved timestamp value.
  42723. */
  42724. async resolveQueriesAsync() {}
  42725. /**
  42726. * Dispose of the query pool.
  42727. *
  42728. * @abstract
  42729. */
  42730. dispose() {}
  42731. }
  42732. /**
  42733. * Manages a pool of WebGL timestamp queries for performance measurement.
  42734. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  42735. *
  42736. * @augments TimestampQueryPool
  42737. */
  42738. class WebGLTimestampQueryPool extends TimestampQueryPool {
  42739. /**
  42740. * Creates a new WebGL timestamp query pool.
  42741. *
  42742. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  42743. * @param {string} type - The type identifier for this query pool.
  42744. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  42745. */
  42746. constructor( gl, type, maxQueries = 2048 ) {
  42747. super( maxQueries );
  42748. this.gl = gl;
  42749. this.type = type;
  42750. // Check for timer query extensions
  42751. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  42752. gl.getExtension( 'EXT_disjoint_timer_query' );
  42753. if ( ! this.ext ) {
  42754. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  42755. this.trackTimestamp = false;
  42756. return;
  42757. }
  42758. // Create query objects
  42759. this.queries = [];
  42760. for ( let i = 0; i < this.maxQueries; i ++ ) {
  42761. this.queries.push( gl.createQuery() );
  42762. }
  42763. this.activeQuery = null;
  42764. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  42765. }
  42766. /**
  42767. * Allocates a pair of queries for a given render context.
  42768. *
  42769. * @param {Object} renderContext - The render context to allocate queries for.
  42770. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  42771. */
  42772. allocateQueriesForContext( renderContext ) {
  42773. if ( ! this.trackTimestamp ) return null;
  42774. // Check if we have enough space for a new query pair
  42775. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  42776. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  42777. return null;
  42778. }
  42779. const baseOffset = this.currentQueryIndex;
  42780. this.currentQueryIndex += 2;
  42781. // Initialize query states
  42782. this.queryStates.set( baseOffset, 'inactive' );
  42783. this.queryOffsets.set( renderContext.id, baseOffset );
  42784. return baseOffset;
  42785. }
  42786. /**
  42787. * Begins a timestamp query for the specified render context.
  42788. *
  42789. * @param {Object} renderContext - The render context to begin timing for.
  42790. */
  42791. beginQuery( renderContext ) {
  42792. if ( ! this.trackTimestamp || this.isDisposed ) {
  42793. return;
  42794. }
  42795. const baseOffset = this.queryOffsets.get( renderContext.id );
  42796. if ( baseOffset == null ) {
  42797. return;
  42798. }
  42799. // Don't start a new query if there's an active one
  42800. if ( this.activeQuery !== null ) {
  42801. return;
  42802. }
  42803. const query = this.queries[ baseOffset ];
  42804. if ( ! query ) {
  42805. return;
  42806. }
  42807. try {
  42808. // Only begin if query is inactive
  42809. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  42810. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  42811. this.activeQuery = baseOffset;
  42812. this.queryStates.set( baseOffset, 'started' );
  42813. }
  42814. } catch ( error ) {
  42815. console.error( 'Error in beginQuery:', error );
  42816. this.activeQuery = null;
  42817. this.queryStates.set( baseOffset, 'inactive' );
  42818. }
  42819. }
  42820. /**
  42821. * Ends the active timestamp query for the specified render context.
  42822. *
  42823. * @param {Object} renderContext - The render context to end timing for.
  42824. * @param {string} renderContext.id - Unique identifier for the render context.
  42825. */
  42826. endQuery( renderContext ) {
  42827. if ( ! this.trackTimestamp || this.isDisposed ) {
  42828. return;
  42829. }
  42830. const baseOffset = this.queryOffsets.get( renderContext.id );
  42831. if ( baseOffset == null ) {
  42832. return;
  42833. }
  42834. // Only end if this is the active query
  42835. if ( this.activeQuery !== baseOffset ) {
  42836. return;
  42837. }
  42838. try {
  42839. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  42840. this.queryStates.set( baseOffset, 'ended' );
  42841. this.activeQuery = null;
  42842. } catch ( error ) {
  42843. console.error( 'Error in endQuery:', error );
  42844. // Reset state on error
  42845. this.queryStates.set( baseOffset, 'inactive' );
  42846. this.activeQuery = null;
  42847. }
  42848. }
  42849. /**
  42850. * Asynchronously resolves all completed queries and returns the total duration.
  42851. *
  42852. * @async
  42853. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  42854. */
  42855. async resolveQueriesAsync() {
  42856. if ( ! this.trackTimestamp || this.pendingResolve ) {
  42857. return this.lastValue;
  42858. }
  42859. this.pendingResolve = true;
  42860. try {
  42861. // Wait for all ended queries to complete
  42862. const resolvePromises = [];
  42863. for ( const [ baseOffset, state ] of this.queryStates ) {
  42864. if ( state === 'ended' ) {
  42865. const query = this.queries[ baseOffset ];
  42866. resolvePromises.push( this.resolveQuery( query ) );
  42867. }
  42868. }
  42869. if ( resolvePromises.length === 0 ) {
  42870. return this.lastValue;
  42871. }
  42872. const results = await Promise.all( resolvePromises );
  42873. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  42874. // Store the last valid result
  42875. this.lastValue = totalDuration;
  42876. // Reset states
  42877. this.currentQueryIndex = 0;
  42878. this.queryOffsets.clear();
  42879. this.queryStates.clear();
  42880. this.activeQuery = null;
  42881. return totalDuration;
  42882. } catch ( error ) {
  42883. console.error( 'Error resolving queries:', error );
  42884. return this.lastValue;
  42885. } finally {
  42886. this.pendingResolve = false;
  42887. }
  42888. }
  42889. /**
  42890. * Resolves a single query, checking for completion and disjoint operation.
  42891. *
  42892. * @async
  42893. * @param {WebGLQuery} query - The query object to resolve.
  42894. * @returns {Promise<number>} The elapsed time in milliseconds.
  42895. */
  42896. async resolveQuery( query ) {
  42897. return new Promise( ( resolve ) => {
  42898. if ( this.isDisposed ) {
  42899. resolve( this.lastValue );
  42900. return;
  42901. }
  42902. let timeoutId;
  42903. let isResolved = false;
  42904. const cleanup = () => {
  42905. if ( timeoutId ) {
  42906. clearTimeout( timeoutId );
  42907. timeoutId = null;
  42908. }
  42909. };
  42910. const finalizeResolution = ( value ) => {
  42911. if ( ! isResolved ) {
  42912. isResolved = true;
  42913. cleanup();
  42914. resolve( value );
  42915. }
  42916. };
  42917. const checkQuery = () => {
  42918. if ( this.isDisposed ) {
  42919. finalizeResolution( this.lastValue );
  42920. return;
  42921. }
  42922. try {
  42923. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  42924. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  42925. if ( disjoint ) {
  42926. finalizeResolution( this.lastValue );
  42927. return;
  42928. }
  42929. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  42930. if ( ! available ) {
  42931. timeoutId = setTimeout( checkQuery, 1 );
  42932. return;
  42933. }
  42934. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  42935. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  42936. } catch ( error ) {
  42937. console.error( 'Error checking query:', error );
  42938. resolve( this.lastValue );
  42939. }
  42940. };
  42941. checkQuery();
  42942. } );
  42943. }
  42944. /**
  42945. * Releases all resources held by this query pool.
  42946. * This includes deleting all query objects and clearing internal state.
  42947. */
  42948. dispose() {
  42949. if ( this.isDisposed ) {
  42950. return;
  42951. }
  42952. this.isDisposed = true;
  42953. if ( ! this.trackTimestamp ) return;
  42954. for ( const query of this.queries ) {
  42955. this.gl.deleteQuery( query );
  42956. }
  42957. this.queries = [];
  42958. this.queryStates.clear();
  42959. this.queryOffsets.clear();
  42960. this.lastValue = 0;
  42961. this.activeQuery = null;
  42962. }
  42963. }
  42964. /**
  42965. * A backend implementation targeting WebGL 2.
  42966. *
  42967. * @private
  42968. * @augments Backend
  42969. */
  42970. class WebGLBackend extends Backend {
  42971. /**
  42972. * WebGLBackend options.
  42973. *
  42974. * @typedef {Object} WebGLBackend~Options
  42975. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  42976. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  42977. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  42978. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  42979. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  42980. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  42981. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  42982. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  42983. */
  42984. /**
  42985. * Constructs a new WebGPU backend.
  42986. *
  42987. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  42988. */
  42989. constructor( parameters = {} ) {
  42990. super( parameters );
  42991. /**
  42992. * This flag can be used for type testing.
  42993. *
  42994. * @type {boolean}
  42995. * @readonly
  42996. * @default true
  42997. */
  42998. this.isWebGLBackend = true;
  42999. /**
  43000. * A reference to a backend module holding shader attribute-related
  43001. * utility functions.
  43002. *
  43003. * @type {?WebGLAttributeUtils}
  43004. * @default null
  43005. */
  43006. this.attributeUtils = null;
  43007. /**
  43008. * A reference to a backend module holding extension-related
  43009. * utility functions.
  43010. *
  43011. * @type {?WebGLExtensions}
  43012. * @default null
  43013. */
  43014. this.extensions = null;
  43015. /**
  43016. * A reference to a backend module holding capability-related
  43017. * utility functions.
  43018. *
  43019. * @type {?WebGLCapabilities}
  43020. * @default null
  43021. */
  43022. this.capabilities = null;
  43023. /**
  43024. * A reference to a backend module holding texture-related
  43025. * utility functions.
  43026. *
  43027. * @type {?WebGLTextureUtils}
  43028. * @default null
  43029. */
  43030. this.textureUtils = null;
  43031. /**
  43032. * A reference to a backend module holding renderer-related
  43033. * utility functions.
  43034. *
  43035. * @type {?WebGLBufferRenderer}
  43036. * @default null
  43037. */
  43038. this.bufferRenderer = null;
  43039. /**
  43040. * A reference to the rendering context.
  43041. *
  43042. * @type {?WebGL2RenderingContext}
  43043. * @default null
  43044. */
  43045. this.gl = null;
  43046. /**
  43047. * A reference to a backend module holding state-related
  43048. * utility functions.
  43049. *
  43050. * @type {?WebGLState}
  43051. * @default null
  43052. */
  43053. this.state = null;
  43054. /**
  43055. * A reference to a backend module holding common
  43056. * utility functions.
  43057. *
  43058. * @type {?WebGLUtils}
  43059. * @default null
  43060. */
  43061. this.utils = null;
  43062. /**
  43063. * Dictionary for caching VAOs.
  43064. *
  43065. * @type {Object<string,WebGLVertexArrayObject>}
  43066. */
  43067. this.vaoCache = {};
  43068. /**
  43069. * Dictionary for caching transform feedback objects.
  43070. *
  43071. * @type {Object<string,WebGLTransformFeedback>}
  43072. */
  43073. this.transformFeedbackCache = {};
  43074. /**
  43075. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  43076. * Only relevant when using compute shaders.
  43077. *
  43078. * @type {boolean}
  43079. * @default false
  43080. */
  43081. this.discard = false;
  43082. /**
  43083. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  43084. * device does not support the extension.
  43085. *
  43086. * @type {?EXTDisjointTimerQueryWebGL2}
  43087. * @default null
  43088. */
  43089. this.disjoint = null;
  43090. /**
  43091. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  43092. * device does not support the extension.
  43093. *
  43094. * @type {?KHRParallelShaderCompile}
  43095. * @default null
  43096. */
  43097. this.parallel = null;
  43098. /**
  43099. * A reference to the current render context.
  43100. *
  43101. * @private
  43102. * @type {RenderContext}
  43103. * @default null
  43104. */
  43105. this._currentContext = null;
  43106. /**
  43107. * A unique collection of bindings.
  43108. *
  43109. * @private
  43110. * @type {WeakSet}
  43111. */
  43112. this._knownBindings = new WeakSet();
  43113. /**
  43114. * Whether the device supports framebuffers invalidation or not.
  43115. *
  43116. * @private
  43117. * @type {boolean}
  43118. */
  43119. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  43120. /**
  43121. * The target framebuffer when rendering with
  43122. * the WebXR device API.
  43123. *
  43124. * @private
  43125. * @type {WebGLFramebuffer}
  43126. * @default null
  43127. */
  43128. this._xrFramebuffer = null;
  43129. }
  43130. /**
  43131. * Initializes the backend so it is ready for usage.
  43132. *
  43133. * @param {Renderer} renderer - The renderer.
  43134. */
  43135. init( renderer ) {
  43136. super.init( renderer );
  43137. //
  43138. const parameters = this.parameters;
  43139. const contextAttributes = {
  43140. antialias: renderer.samples > 0,
  43141. alpha: true, // always true for performance reasons
  43142. depth: renderer.depth,
  43143. stencil: renderer.stencil
  43144. };
  43145. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  43146. function onContextLost( event ) {
  43147. event.preventDefault();
  43148. const contextLossInfo = {
  43149. api: 'WebGL',
  43150. message: event.statusMessage || 'Unknown reason',
  43151. reason: null,
  43152. originalEvent: event
  43153. };
  43154. renderer.onDeviceLost( contextLossInfo );
  43155. }
  43156. this._onContextLost = onContextLost;
  43157. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  43158. this.gl = glContext;
  43159. this.extensions = new WebGLExtensions( this );
  43160. this.capabilities = new WebGLCapabilities( this );
  43161. this.attributeUtils = new WebGLAttributeUtils( this );
  43162. this.textureUtils = new WebGLTextureUtils( this );
  43163. this.bufferRenderer = new WebGLBufferRenderer( this );
  43164. this.state = new WebGLState( this );
  43165. this.utils = new WebGLUtils( this );
  43166. this.extensions.get( 'EXT_color_buffer_float' );
  43167. this.extensions.get( 'WEBGL_clip_cull_distance' );
  43168. this.extensions.get( 'OES_texture_float_linear' );
  43169. this.extensions.get( 'EXT_color_buffer_half_float' );
  43170. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43171. this.extensions.get( 'WEBGL_render_shared_exponent' );
  43172. this.extensions.get( 'WEBGL_multi_draw' );
  43173. this.extensions.get( 'OVR_multiview2' );
  43174. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  43175. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  43176. }
  43177. /**
  43178. * The coordinate system of the backend.
  43179. *
  43180. * @type {number}
  43181. * @readonly
  43182. */
  43183. get coordinateSystem() {
  43184. return WebGLCoordinateSystem;
  43185. }
  43186. /**
  43187. * This method performs a readback operation by moving buffer data from
  43188. * a storage buffer attribute from the GPU to the CPU.
  43189. *
  43190. * @async
  43191. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43192. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43193. */
  43194. async getArrayBufferAsync( attribute ) {
  43195. return await this.attributeUtils.getArrayBufferAsync( attribute );
  43196. }
  43197. /**
  43198. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43199. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43200. *
  43201. * @async
  43202. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43203. */
  43204. async waitForGPU() {
  43205. await this.utils._clientWaitAsync();
  43206. }
  43207. /**
  43208. * Ensures the backend is XR compatible.
  43209. *
  43210. * @async
  43211. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  43212. */
  43213. async makeXRCompatible() {
  43214. const attributes = this.gl.getContextAttributes();
  43215. if ( attributes.xrCompatible !== true ) {
  43216. await this.gl.makeXRCompatible();
  43217. }
  43218. }
  43219. /**
  43220. * Sets the XR rendering destination.
  43221. *
  43222. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  43223. */
  43224. setXRTarget( xrFramebuffer ) {
  43225. this._xrFramebuffer = xrFramebuffer;
  43226. }
  43227. /**
  43228. * Configures the given XR render target with external textures.
  43229. *
  43230. * This method is only relevant when using the WebXR Layers API.
  43231. *
  43232. * @param {XRRenderTarget} renderTarget - The XR render target.
  43233. * @param {WebGLTexture} colorTexture - A native color texture.
  43234. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  43235. */
  43236. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  43237. const gl = this.gl;
  43238. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  43239. if ( depthTexture !== null ) {
  43240. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  43241. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  43242. // The multisample_render_to_texture extension doesn't work properly if there
  43243. // are midframe flushes and an external depth texture.
  43244. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget.autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  43245. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  43246. }
  43247. renderTarget.autoAllocateDepthBuffer = false;
  43248. }
  43249. }
  43250. /**
  43251. * Inits a time stamp query for the given render context.
  43252. *
  43253. * @param {RenderContext} renderContext - The render context.
  43254. */
  43255. initTimestampQuery( renderContext ) {
  43256. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43257. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43258. if ( ! this.timestampQueryPool[ type ] ) {
  43259. // TODO: Variable maxQueries?
  43260. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  43261. }
  43262. const timestampQueryPool = this.timestampQueryPool[ type ];
  43263. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  43264. if ( baseOffset !== null ) {
  43265. timestampQueryPool.beginQuery( renderContext );
  43266. }
  43267. }
  43268. // timestamp utils
  43269. /**
  43270. * Prepares the timestamp buffer.
  43271. *
  43272. * @param {RenderContext} renderContext - The render context.
  43273. */
  43274. prepareTimestampBuffer( renderContext ) {
  43275. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43276. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43277. const timestampQueryPool = this.timestampQueryPool[ type ];
  43278. timestampQueryPool.endQuery( renderContext );
  43279. }
  43280. /**
  43281. * Returns the backend's rendering context.
  43282. *
  43283. * @return {WebGL2RenderingContext} The rendering context.
  43284. */
  43285. getContext() {
  43286. return this.gl;
  43287. }
  43288. /**
  43289. * This method is executed at the beginning of a render call and prepares
  43290. * the WebGL state for upcoming render calls
  43291. *
  43292. * @param {RenderContext} renderContext - The render context.
  43293. */
  43294. beginRender( renderContext ) {
  43295. const { state, gl } = this;
  43296. const renderContextData = this.get( renderContext );
  43297. //
  43298. if ( renderContext.viewport ) {
  43299. this.updateViewport( renderContext );
  43300. } else {
  43301. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  43302. }
  43303. if ( renderContext.scissor ) {
  43304. const { x, y, width, height } = renderContext.scissorValue;
  43305. state.scissor( x, renderContext.height - height - y, width, height );
  43306. }
  43307. //
  43308. this.initTimestampQuery( renderContext );
  43309. renderContextData.previousContext = this._currentContext;
  43310. this._currentContext = renderContext;
  43311. this._setFramebuffer( renderContext );
  43312. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  43313. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43314. if ( occlusionQueryCount > 0 ) {
  43315. // Get a reference to the array of objects with queries. The renderContextData property
  43316. // can be changed by another render pass before the async reading of all previous queries complete
  43317. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  43318. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  43319. renderContextData.lastOcclusionObject = null;
  43320. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  43321. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  43322. renderContextData.occlusionQueryIndex = 0;
  43323. }
  43324. }
  43325. /**
  43326. * This method is executed at the end of a render call and finalizes work
  43327. * after draw calls.
  43328. *
  43329. * @param {RenderContext} renderContext - The render context.
  43330. */
  43331. finishRender( renderContext ) {
  43332. const { gl, state } = this;
  43333. const renderContextData = this.get( renderContext );
  43334. const previousContext = renderContextData.previousContext;
  43335. state.resetVertexState();
  43336. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43337. if ( occlusionQueryCount > 0 ) {
  43338. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43339. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  43340. }
  43341. this.resolveOccludedAsync( renderContext );
  43342. }
  43343. const textures = renderContext.textures;
  43344. if ( textures !== null ) {
  43345. for ( let i = 0; i < textures.length; i ++ ) {
  43346. const texture = textures[ i ];
  43347. if ( texture.generateMipmaps ) {
  43348. this.generateMipmaps( texture );
  43349. }
  43350. }
  43351. }
  43352. this._currentContext = previousContext;
  43353. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  43354. const renderTargetContextData = this.get( renderContext.renderTarget );
  43355. const { samples } = renderContext.renderTarget;
  43356. if ( samples > 0 && this._useMultisampledExtension( renderContext.renderTarget ) === false ) {
  43357. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43358. const mask = gl.COLOR_BUFFER_BIT;
  43359. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43360. const textures = renderContext.textures;
  43361. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  43362. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43363. for ( let i = 0; i < textures.length; i ++ ) {
  43364. // TODO Add support for MRT
  43365. if ( renderContext.scissor ) {
  43366. const { x, y, width, height } = renderContext.scissorValue;
  43367. const viewY = renderContext.height - height - y;
  43368. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  43369. if ( this._supportsInvalidateFramebuffer === true ) {
  43370. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  43371. }
  43372. } else {
  43373. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  43374. if ( this._supportsInvalidateFramebuffer === true ) {
  43375. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  43376. }
  43377. }
  43378. }
  43379. }
  43380. }
  43381. if ( previousContext !== null ) {
  43382. this._setFramebuffer( previousContext );
  43383. if ( previousContext.viewport ) {
  43384. this.updateViewport( previousContext );
  43385. } else {
  43386. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  43387. }
  43388. }
  43389. this.prepareTimestampBuffer( renderContext );
  43390. }
  43391. /**
  43392. * This method processes the result of occlusion queries and writes it
  43393. * into render context data.
  43394. *
  43395. * @async
  43396. * @param {RenderContext} renderContext - The render context.
  43397. */
  43398. resolveOccludedAsync( renderContext ) {
  43399. const renderContextData = this.get( renderContext );
  43400. // handle occlusion query results
  43401. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  43402. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  43403. const occluded = new WeakSet();
  43404. const { gl } = this;
  43405. renderContextData.currentOcclusionQueryObjects = null;
  43406. renderContextData.currentOcclusionQueries = null;
  43407. const check = () => {
  43408. let completed = 0;
  43409. // check all queries and requeue as appropriate
  43410. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  43411. const query = currentOcclusionQueries[ i ];
  43412. if ( query === null ) continue;
  43413. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  43414. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  43415. currentOcclusionQueries[ i ] = null;
  43416. gl.deleteQuery( query );
  43417. completed ++;
  43418. }
  43419. }
  43420. if ( completed < currentOcclusionQueries.length ) {
  43421. requestAnimationFrame( check );
  43422. } else {
  43423. renderContextData.occluded = occluded;
  43424. }
  43425. };
  43426. check();
  43427. }
  43428. }
  43429. /**
  43430. * Returns `true` if the given 3D object is fully occluded by other
  43431. * 3D objects in the scene.
  43432. *
  43433. * @param {RenderContext} renderContext - The render context.
  43434. * @param {Object3D} object - The 3D object to test.
  43435. * @return {boolean} Whether the 3D object is fully occluded or not.
  43436. */
  43437. isOccluded( renderContext, object ) {
  43438. const renderContextData = this.get( renderContext );
  43439. return renderContextData.occluded && renderContextData.occluded.has( object );
  43440. }
  43441. /**
  43442. * Updates the viewport with the values from the given render context.
  43443. *
  43444. * @param {RenderContext} renderContext - The render context.
  43445. */
  43446. updateViewport( renderContext ) {
  43447. const { state } = this;
  43448. const { x, y, width, height } = renderContext.viewportValue;
  43449. state.viewport( x, renderContext.height - height - y, width, height );
  43450. }
  43451. /**
  43452. * Defines the scissor test.
  43453. *
  43454. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43455. */
  43456. setScissorTest( boolean ) {
  43457. const state = this.state;
  43458. state.setScissorTest( boolean );
  43459. }
  43460. /**
  43461. * Returns the clear color and alpha into a single
  43462. * color object.
  43463. *
  43464. * @return {Color4} The clear color.
  43465. */
  43466. getClearColor() {
  43467. const clearColor = super.getClearColor();
  43468. // Since the canvas is always created with alpha: true,
  43469. // WebGL must always premultiply the clear color.
  43470. clearColor.r *= clearColor.a;
  43471. clearColor.g *= clearColor.a;
  43472. clearColor.b *= clearColor.a;
  43473. return clearColor;
  43474. }
  43475. /**
  43476. * Performs a clear operation.
  43477. *
  43478. * @param {boolean} color - Whether the color buffer should be cleared or not.
  43479. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  43480. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  43481. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  43482. * @param {boolean} [setFrameBuffer=true] - TODO.
  43483. */
  43484. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  43485. const { gl, renderer } = this;
  43486. if ( descriptor === null ) {
  43487. const clearColor = this.getClearColor();
  43488. descriptor = {
  43489. textures: null,
  43490. clearColorValue: clearColor
  43491. };
  43492. }
  43493. //
  43494. let clear = 0;
  43495. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  43496. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  43497. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  43498. if ( clear !== 0 ) {
  43499. let clearColor;
  43500. if ( descriptor.clearColorValue ) {
  43501. clearColor = descriptor.clearColorValue;
  43502. } else {
  43503. clearColor = this.getClearColor();
  43504. }
  43505. const clearDepth = renderer.getClearDepth();
  43506. const clearStencil = renderer.getClearStencil();
  43507. if ( depth ) this.state.setDepthMask( true );
  43508. if ( descriptor.textures === null ) {
  43509. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  43510. gl.clear( clear );
  43511. } else {
  43512. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  43513. if ( color ) {
  43514. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  43515. if ( i === 0 ) {
  43516. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  43517. } else {
  43518. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  43519. }
  43520. }
  43521. }
  43522. if ( depth && stencil ) {
  43523. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  43524. } else if ( depth ) {
  43525. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  43526. } else if ( stencil ) {
  43527. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  43528. }
  43529. }
  43530. }
  43531. }
  43532. /**
  43533. * This method is executed at the beginning of a compute call and
  43534. * prepares the state for upcoming compute tasks.
  43535. *
  43536. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43537. */
  43538. beginCompute( computeGroup ) {
  43539. const { state, gl } = this;
  43540. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  43541. this.initTimestampQuery( computeGroup );
  43542. }
  43543. /**
  43544. * Executes a compute command for the given compute node.
  43545. *
  43546. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  43547. * @param {Node} computeNode - The compute node.
  43548. * @param {Array<BindGroup>} bindings - The bindings.
  43549. * @param {ComputePipeline} pipeline - The compute pipeline.
  43550. */
  43551. compute( computeGroup, computeNode, bindings, pipeline ) {
  43552. const { state, gl } = this;
  43553. if ( this.discard === false ) {
  43554. // required here to handle async behaviour of render.compute()
  43555. gl.enable( gl.RASTERIZER_DISCARD );
  43556. this.discard = true;
  43557. }
  43558. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  43559. const vaoKey = this._getVaoKey( attributes );
  43560. const vaoGPU = this.vaoCache[ vaoKey ];
  43561. if ( vaoGPU === undefined ) {
  43562. this._createVao( attributes );
  43563. } else {
  43564. state.setVertexState( vaoGPU );
  43565. }
  43566. state.useProgram( programGPU );
  43567. this._bindUniforms( bindings );
  43568. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  43569. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  43570. gl.beginTransformFeedback( gl.POINTS );
  43571. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  43572. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  43573. } else {
  43574. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  43575. }
  43576. gl.endTransformFeedback();
  43577. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  43578. // switch active buffers
  43579. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  43580. const dualAttributeData = transformBuffers[ i ];
  43581. if ( dualAttributeData.pbo ) {
  43582. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  43583. }
  43584. dualAttributeData.switchBuffers();
  43585. }
  43586. }
  43587. /**
  43588. * This method is executed at the end of a compute call and
  43589. * finalizes work after compute tasks.
  43590. *
  43591. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  43592. */
  43593. finishCompute( computeGroup ) {
  43594. const gl = this.gl;
  43595. this.discard = false;
  43596. gl.disable( gl.RASTERIZER_DISCARD );
  43597. this.prepareTimestampBuffer( computeGroup );
  43598. if ( this._currentContext ) {
  43599. this._setFramebuffer( this._currentContext );
  43600. }
  43601. }
  43602. /**
  43603. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  43604. *
  43605. * @param {RenderContext} renderContext - The render context.
  43606. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  43607. *
  43608. * @private
  43609. */
  43610. _isRenderCameraDepthArray( renderContext ) {
  43611. return renderContext.depthTexture && renderContext.depthTexture.isDepthArrayTexture && renderContext.camera.isArrayCamera;
  43612. }
  43613. /**
  43614. * Executes a draw command for the given render object.
  43615. *
  43616. * @param {RenderObject} renderObject - The render object to draw.
  43617. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  43618. */
  43619. draw( renderObject/*, info*/ ) {
  43620. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  43621. const { programGPU } = this.get( pipeline );
  43622. const { gl, state } = this;
  43623. const contextData = this.get( context );
  43624. const drawParams = renderObject.getDrawParameters();
  43625. if ( drawParams === null ) return;
  43626. //
  43627. this._bindUniforms( renderObject.getBindings() );
  43628. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  43629. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  43630. state.useProgram( programGPU );
  43631. // vertex state
  43632. const renderObjectData = this.get( renderObject );
  43633. let vaoGPU = renderObjectData.staticVao;
  43634. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  43635. const vaoKey = this._getVaoKey( renderObject.getAttributes() );
  43636. vaoGPU = this.vaoCache[ vaoKey ];
  43637. if ( vaoGPU === undefined ) {
  43638. let staticVao;
  43639. ( { vaoGPU, staticVao } = this._createVao( renderObject.getAttributes() ) );
  43640. if ( staticVao ) {
  43641. renderObjectData.staticVao = vaoGPU;
  43642. renderObjectData.geometryId = renderObject.geometry.id;
  43643. }
  43644. }
  43645. }
  43646. const index = renderObject.getIndex();
  43647. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  43648. state.setVertexState( vaoGPU, indexGPU );
  43649. //
  43650. const lastObject = contextData.lastOcclusionObject;
  43651. if ( lastObject !== object && lastObject !== undefined ) {
  43652. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  43653. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  43654. contextData.occlusionQueryIndex ++;
  43655. }
  43656. if ( object.occlusionTest === true ) {
  43657. const query = gl.createQuery();
  43658. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  43659. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  43660. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  43661. }
  43662. contextData.lastOcclusionObject = object;
  43663. }
  43664. //
  43665. const renderer = this.bufferRenderer;
  43666. if ( object.isPoints ) renderer.mode = gl.POINTS;
  43667. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  43668. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  43669. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  43670. else {
  43671. if ( material.wireframe === true ) {
  43672. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  43673. renderer.mode = gl.LINES;
  43674. } else {
  43675. renderer.mode = gl.TRIANGLES;
  43676. }
  43677. }
  43678. //
  43679. const { vertexCount, instanceCount } = drawParams;
  43680. let { firstVertex } = drawParams;
  43681. renderer.object = object;
  43682. if ( index !== null ) {
  43683. firstVertex *= index.array.BYTES_PER_ELEMENT;
  43684. const indexData = this.get( index );
  43685. renderer.index = index.count;
  43686. renderer.type = indexData.type;
  43687. } else {
  43688. renderer.index = 0;
  43689. }
  43690. const draw = () => {
  43691. if ( object.isBatchedMesh ) {
  43692. if ( object._multiDrawInstances !== null ) {
  43693. // @deprecated, r174
  43694. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  43695. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  43696. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  43697. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  43698. } else {
  43699. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  43700. }
  43701. } else if ( instanceCount > 1 ) {
  43702. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  43703. } else {
  43704. renderer.render( firstVertex, vertexCount );
  43705. }
  43706. };
  43707. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  43708. const cameraData = this.get( renderObject.camera );
  43709. const cameras = renderObject.camera.cameras;
  43710. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  43711. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  43712. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  43713. const indexesGPU = [];
  43714. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  43715. const bufferGPU = gl.createBuffer();
  43716. data[ 0 ] = i;
  43717. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  43718. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  43719. indexesGPU.push( bufferGPU );
  43720. }
  43721. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  43722. }
  43723. const cameraIndexData = this.get( cameraIndex );
  43724. const pixelRatio = this.renderer.getPixelRatio();
  43725. const renderTarget = this._currentContext.renderTarget;
  43726. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  43727. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  43728. if ( isRenderCameraDepthArray ) {
  43729. // Clear the depth texture
  43730. const textureData = this.get( renderTarget.depthTexture );
  43731. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  43732. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  43733. const { stencilBuffer } = renderTarget;
  43734. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  43735. this.renderer._activeCubeFace = i;
  43736. this._currentContext.activeCubeFace = i;
  43737. this._setFramebuffer( this._currentContext );
  43738. this.clear( false, true, stencilBuffer, this._currentContext, false );
  43739. }
  43740. this.renderer._activeCubeFace = prevActiveCubeFace;
  43741. this._currentContext.activeCubeFace = prevActiveCubeFace;
  43742. }
  43743. }
  43744. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  43745. const subCamera = cameras[ i ];
  43746. if ( object.layers.test( subCamera.layers ) ) {
  43747. if ( isRenderCameraDepthArray ) {
  43748. // Update the active layer
  43749. this.renderer._activeCubeFace = i;
  43750. this._currentContext.activeCubeFace = i;
  43751. this._setFramebuffer( this._currentContext );
  43752. }
  43753. const vp = subCamera.viewport;
  43754. if ( vp !== undefined ) {
  43755. const x = vp.x * pixelRatio;
  43756. const y = vp.y * pixelRatio;
  43757. const width = vp.width * pixelRatio;
  43758. const height = vp.height * pixelRatio;
  43759. state.viewport(
  43760. Math.floor( x ),
  43761. Math.floor( renderObject.context.height - height - y ),
  43762. Math.floor( width ),
  43763. Math.floor( height )
  43764. );
  43765. }
  43766. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  43767. draw();
  43768. }
  43769. this._currentContext.activeCubeFace = prevActiveCubeFace;
  43770. this.renderer._activeCubeFace = prevActiveCubeFace;
  43771. }
  43772. } else {
  43773. draw();
  43774. }
  43775. }
  43776. /**
  43777. * Explain why always null is returned.
  43778. *
  43779. * @param {RenderObject} renderObject - The render object.
  43780. * @return {boolean} Whether the render pipeline requires an update or not.
  43781. */
  43782. needsRenderUpdate( /*renderObject*/ ) {
  43783. return false;
  43784. }
  43785. /**
  43786. * Explain why no cache key is computed.
  43787. *
  43788. * @param {RenderObject} renderObject - The render object.
  43789. * @return {string} The cache key.
  43790. */
  43791. getRenderCacheKey( /*renderObject*/ ) {
  43792. return '';
  43793. }
  43794. // textures
  43795. /**
  43796. * Creates a default texture for the given texture that can be used
  43797. * as a placeholder until the actual texture is ready for usage.
  43798. *
  43799. * @param {Texture} texture - The texture to create a default texture for.
  43800. */
  43801. createDefaultTexture( texture ) {
  43802. this.textureUtils.createDefaultTexture( texture );
  43803. }
  43804. /**
  43805. * Defines a texture on the GPU for the given texture object.
  43806. *
  43807. * @param {Texture} texture - The texture.
  43808. * @param {Object} [options={}] - Optional configuration parameter.
  43809. */
  43810. createTexture( texture, options ) {
  43811. this.textureUtils.createTexture( texture, options );
  43812. }
  43813. /**
  43814. * Uploads the updated texture data to the GPU.
  43815. *
  43816. * @param {Texture} texture - The texture.
  43817. * @param {Object} [options={}] - Optional configuration parameter.
  43818. */
  43819. updateTexture( texture, options ) {
  43820. this.textureUtils.updateTexture( texture, options );
  43821. }
  43822. /**
  43823. * Generates mipmaps for the given texture.
  43824. *
  43825. * @param {Texture} texture - The texture.
  43826. */
  43827. generateMipmaps( texture ) {
  43828. this.textureUtils.generateMipmaps( texture );
  43829. }
  43830. /**
  43831. * Destroys the GPU data for the given texture object.
  43832. *
  43833. * @param {Texture} texture - The texture.
  43834. */
  43835. destroyTexture( texture ) {
  43836. this.textureUtils.destroyTexture( texture );
  43837. }
  43838. /**
  43839. * Returns texture data as a typed array.
  43840. *
  43841. * @async
  43842. * @param {Texture} texture - The texture to copy.
  43843. * @param {number} x - The x coordinate of the copy origin.
  43844. * @param {number} y - The y coordinate of the copy origin.
  43845. * @param {number} width - The width of the copy.
  43846. * @param {number} height - The height of the copy.
  43847. * @param {number} faceIndex - The face index.
  43848. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43849. */
  43850. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43851. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  43852. }
  43853. /**
  43854. * This method does nothing since WebGL 2 has no concept of samplers.
  43855. *
  43856. * @param {Texture} texture - The texture to create the sampler for.
  43857. */
  43858. createSampler( /*texture*/ ) {
  43859. //console.warn( 'Abstract class.' );
  43860. }
  43861. /**
  43862. * This method does nothing since WebGL 2 has no concept of samplers.
  43863. *
  43864. * @param {Texture} texture - The texture to destroy the sampler for.
  43865. */
  43866. destroySampler( /*texture*/ ) {}
  43867. // node builder
  43868. /**
  43869. * Returns a node builder for the given render object.
  43870. *
  43871. * @param {RenderObject} object - The render object.
  43872. * @param {Renderer} renderer - The renderer.
  43873. * @return {GLSLNodeBuilder} The node builder.
  43874. */
  43875. createNodeBuilder( object, renderer ) {
  43876. return new GLSLNodeBuilder( object, renderer );
  43877. }
  43878. // program
  43879. /**
  43880. * Creates a shader program from the given programmable stage.
  43881. *
  43882. * @param {ProgrammableStage} program - The programmable stage.
  43883. */
  43884. createProgram( program ) {
  43885. const gl = this.gl;
  43886. const { stage, code } = program;
  43887. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  43888. gl.shaderSource( shader, code );
  43889. gl.compileShader( shader );
  43890. this.set( program, {
  43891. shaderGPU: shader
  43892. } );
  43893. }
  43894. /**
  43895. * Destroys the shader program of the given programmable stage.
  43896. *
  43897. * @param {ProgrammableStage} program - The programmable stage.
  43898. */
  43899. destroyProgram( program ) {
  43900. this.delete( program );
  43901. }
  43902. /**
  43903. * Creates a render pipeline for the given render object.
  43904. *
  43905. * @param {RenderObject} renderObject - The render object.
  43906. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  43907. */
  43908. createRenderPipeline( renderObject, promises ) {
  43909. const gl = this.gl;
  43910. const pipeline = renderObject.pipeline;
  43911. // Program
  43912. const { fragmentProgram, vertexProgram } = pipeline;
  43913. const programGPU = gl.createProgram();
  43914. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  43915. const vertexShader = this.get( vertexProgram ).shaderGPU;
  43916. gl.attachShader( programGPU, fragmentShader );
  43917. gl.attachShader( programGPU, vertexShader );
  43918. gl.linkProgram( programGPU );
  43919. this.set( pipeline, {
  43920. programGPU,
  43921. fragmentShader,
  43922. vertexShader
  43923. } );
  43924. if ( promises !== null && this.parallel ) {
  43925. const p = new Promise( ( resolve /*, reject*/ ) => {
  43926. const parallel = this.parallel;
  43927. const checkStatus = () => {
  43928. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  43929. this._completeCompile( renderObject, pipeline );
  43930. resolve();
  43931. } else {
  43932. requestAnimationFrame( checkStatus );
  43933. }
  43934. };
  43935. checkStatus();
  43936. } );
  43937. promises.push( p );
  43938. return;
  43939. }
  43940. this._completeCompile( renderObject, pipeline );
  43941. }
  43942. /**
  43943. * Formats the source code of error messages.
  43944. *
  43945. * @private
  43946. * @param {string} string - The code.
  43947. * @param {number} errorLine - The error line.
  43948. * @return {string} The formatted code.
  43949. */
  43950. _handleSource( string, errorLine ) {
  43951. const lines = string.split( '\n' );
  43952. const lines2 = [];
  43953. const from = Math.max( errorLine - 6, 0 );
  43954. const to = Math.min( errorLine + 6, lines.length );
  43955. for ( let i = from; i < to; i ++ ) {
  43956. const line = i + 1;
  43957. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  43958. }
  43959. return lines2.join( '\n' );
  43960. }
  43961. /**
  43962. * Gets the shader compilation errors from the info log.
  43963. *
  43964. * @private
  43965. * @param {WebGL2RenderingContext} gl - The rendering context.
  43966. * @param {WebGLShader} shader - The WebGL shader object.
  43967. * @param {string} type - The shader type.
  43968. * @return {string} The shader errors.
  43969. */
  43970. _getShaderErrors( gl, shader, type ) {
  43971. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  43972. const errors = gl.getShaderInfoLog( shader ).trim();
  43973. if ( status && errors === '' ) return '';
  43974. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  43975. if ( errorMatches ) {
  43976. const errorLine = parseInt( errorMatches[ 1 ] );
  43977. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  43978. } else {
  43979. return errors;
  43980. }
  43981. }
  43982. /**
  43983. * Logs shader compilation errors.
  43984. *
  43985. * @private
  43986. * @param {WebGLProgram} programGPU - The WebGL program.
  43987. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  43988. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  43989. */
  43990. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  43991. if ( this.renderer.debug.checkShaderErrors ) {
  43992. const gl = this.gl;
  43993. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  43994. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  43995. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  43996. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  43997. } else {
  43998. // default error reporting
  43999. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  44000. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  44001. console.error(
  44002. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  44003. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  44004. 'Program Info Log: ' + programLog + '\n' +
  44005. vertexErrors + '\n' +
  44006. fragmentErrors
  44007. );
  44008. }
  44009. } else if ( programLog !== '' ) {
  44010. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  44011. }
  44012. }
  44013. }
  44014. /**
  44015. * Completes the shader program setup for the given render object.
  44016. *
  44017. * @private
  44018. * @param {RenderObject} renderObject - The render object.
  44019. * @param {RenderPipeline} pipeline - The render pipeline.
  44020. */
  44021. _completeCompile( renderObject, pipeline ) {
  44022. const { state, gl } = this;
  44023. const pipelineData = this.get( pipeline );
  44024. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  44025. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44026. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44027. }
  44028. state.useProgram( programGPU );
  44029. // Bindings
  44030. const bindings = renderObject.getBindings();
  44031. this._setupBindings( bindings, programGPU );
  44032. //
  44033. this.set( pipeline, {
  44034. programGPU
  44035. } );
  44036. }
  44037. /**
  44038. * Creates a compute pipeline for the given compute node.
  44039. *
  44040. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44041. * @param {Array<BindGroup>} bindings - The bindings.
  44042. */
  44043. createComputePipeline( computePipeline, bindings ) {
  44044. const { state, gl } = this;
  44045. // Program
  44046. const fragmentProgram = {
  44047. stage: 'fragment',
  44048. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  44049. };
  44050. this.createProgram( fragmentProgram );
  44051. const { computeProgram } = computePipeline;
  44052. const programGPU = gl.createProgram();
  44053. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44054. const vertexShader = this.get( computeProgram ).shaderGPU;
  44055. const transforms = computeProgram.transforms;
  44056. const transformVaryingNames = [];
  44057. const transformAttributeNodes = [];
  44058. for ( let i = 0; i < transforms.length; i ++ ) {
  44059. const transform = transforms[ i ];
  44060. transformVaryingNames.push( transform.varyingName );
  44061. transformAttributeNodes.push( transform.attributeNode );
  44062. }
  44063. gl.attachShader( programGPU, fragmentShader );
  44064. gl.attachShader( programGPU, vertexShader );
  44065. gl.transformFeedbackVaryings(
  44066. programGPU,
  44067. transformVaryingNames,
  44068. gl.SEPARATE_ATTRIBS
  44069. );
  44070. gl.linkProgram( programGPU );
  44071. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44072. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44073. }
  44074. state.useProgram( programGPU );
  44075. // Bindings
  44076. this._setupBindings( bindings, programGPU );
  44077. const attributeNodes = computeProgram.attributes;
  44078. const attributes = [];
  44079. const transformBuffers = [];
  44080. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  44081. const attribute = attributeNodes[ i ].node.attribute;
  44082. attributes.push( attribute );
  44083. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44084. }
  44085. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  44086. const attribute = transformAttributeNodes[ i ].attribute;
  44087. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44088. const attributeData = this.get( attribute );
  44089. transformBuffers.push( attributeData );
  44090. }
  44091. //
  44092. this.set( computePipeline, {
  44093. programGPU,
  44094. transformBuffers,
  44095. attributes
  44096. } );
  44097. }
  44098. /**
  44099. * Creates bindings from the given bind group definition.
  44100. *
  44101. * @param {BindGroup} bindGroup - The bind group.
  44102. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44103. * @param {number} cacheIndex - The cache index.
  44104. * @param {number} version - The version.
  44105. */
  44106. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  44107. if ( this._knownBindings.has( bindings ) === false ) {
  44108. this._knownBindings.add( bindings );
  44109. let uniformBuffers = 0;
  44110. let textures = 0;
  44111. for ( const bindGroup of bindings ) {
  44112. this.set( bindGroup, {
  44113. textures: textures,
  44114. uniformBuffers: uniformBuffers
  44115. } );
  44116. for ( const binding of bindGroup.bindings ) {
  44117. if ( binding.isUniformBuffer ) uniformBuffers ++;
  44118. if ( binding.isSampledTexture ) textures ++;
  44119. }
  44120. }
  44121. }
  44122. this.updateBindings( bindGroup, bindings );
  44123. }
  44124. /**
  44125. * Updates the given bind group definition.
  44126. *
  44127. * @param {BindGroup} bindGroup - The bind group.
  44128. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44129. * @param {number} cacheIndex - The cache index.
  44130. * @param {number} version - The version.
  44131. */
  44132. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  44133. const { gl } = this;
  44134. const bindGroupData = this.get( bindGroup );
  44135. let i = bindGroupData.uniformBuffers;
  44136. let t = bindGroupData.textures;
  44137. for ( const binding of bindGroup.bindings ) {
  44138. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44139. const data = binding.buffer;
  44140. const bufferGPU = gl.createBuffer();
  44141. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44142. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44143. this.set( binding, {
  44144. index: i ++,
  44145. bufferGPU
  44146. } );
  44147. } else if ( binding.isSampledTexture ) {
  44148. const { textureGPU, glTextureType } = this.get( binding.texture );
  44149. this.set( binding, {
  44150. index: t ++,
  44151. textureGPU,
  44152. glTextureType
  44153. } );
  44154. }
  44155. }
  44156. }
  44157. /**
  44158. * Updates a buffer binding.
  44159. *
  44160. * @param {Buffer} binding - The buffer binding to update.
  44161. */
  44162. updateBinding( binding ) {
  44163. const gl = this.gl;
  44164. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44165. const bindingData = this.get( binding );
  44166. const bufferGPU = bindingData.bufferGPU;
  44167. const data = binding.buffer;
  44168. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44169. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44170. }
  44171. }
  44172. // attributes
  44173. /**
  44174. * Creates the GPU buffer of an indexed shader attribute.
  44175. *
  44176. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  44177. */
  44178. createIndexAttribute( attribute ) {
  44179. const gl = this.gl;
  44180. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  44181. }
  44182. /**
  44183. * Creates the GPU buffer of a shader attribute.
  44184. *
  44185. * @param {BufferAttribute} attribute - The buffer attribute.
  44186. */
  44187. createAttribute( attribute ) {
  44188. if ( this.has( attribute ) ) return;
  44189. const gl = this.gl;
  44190. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44191. }
  44192. /**
  44193. * Creates the GPU buffer of a storage attribute.
  44194. *
  44195. * @param {BufferAttribute} attribute - The buffer attribute.
  44196. */
  44197. createStorageAttribute( attribute ) {
  44198. if ( this.has( attribute ) ) return;
  44199. const gl = this.gl;
  44200. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44201. }
  44202. /**
  44203. * Updates the GPU buffer of a shader attribute.
  44204. *
  44205. * @param {BufferAttribute} attribute - The buffer attribute to update.
  44206. */
  44207. updateAttribute( attribute ) {
  44208. this.attributeUtils.updateAttribute( attribute );
  44209. }
  44210. /**
  44211. * Destroys the GPU buffer of a shader attribute.
  44212. *
  44213. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  44214. */
  44215. destroyAttribute( attribute ) {
  44216. this.attributeUtils.destroyAttribute( attribute );
  44217. }
  44218. /**
  44219. * Checks if the given feature is supported by the backend.
  44220. *
  44221. * @param {string} name - The feature's name.
  44222. * @return {boolean} Whether the feature is supported or not.
  44223. */
  44224. hasFeature( name ) {
  44225. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  44226. const extensions = this.extensions;
  44227. for ( let i = 0; i < keysMatching.length; i ++ ) {
  44228. if ( extensions.has( keysMatching[ i ] ) ) return true;
  44229. }
  44230. return false;
  44231. }
  44232. /**
  44233. * Returns the maximum anisotropy texture filtering value.
  44234. *
  44235. * @return {number} The maximum anisotropy texture filtering value.
  44236. */
  44237. getMaxAnisotropy() {
  44238. return this.capabilities.getMaxAnisotropy();
  44239. }
  44240. /**
  44241. * Copies data of the given source texture to the given destination texture.
  44242. *
  44243. * @param {Texture} srcTexture - The source texture.
  44244. * @param {Texture} dstTexture - The destination texture.
  44245. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44246. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44247. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44248. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44249. */
  44250. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44251. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  44252. }
  44253. /**
  44254. * Copies the current bound framebuffer to the given texture.
  44255. *
  44256. * @param {Texture} texture - The destination texture.
  44257. * @param {RenderContext} renderContext - The render context.
  44258. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44259. */
  44260. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  44261. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  44262. }
  44263. /**
  44264. * Configures the active framebuffer from the given render context.
  44265. *
  44266. * @private
  44267. * @param {RenderContext} descriptor - The render context.
  44268. */
  44269. _setFramebuffer( descriptor ) {
  44270. const { gl, state } = this;
  44271. let currentFrameBuffer = null;
  44272. if ( descriptor.textures !== null ) {
  44273. const renderTarget = descriptor.renderTarget;
  44274. const renderTargetContextData = this.get( renderTarget );
  44275. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  44276. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  44277. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  44278. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  44279. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  44280. const hasExternalTextures = ( isXRRenderTarget === true && renderTarget.hasExternalTextures === true );
  44281. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  44282. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  44283. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44284. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  44285. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  44286. const cacheKey = getCacheKey( descriptor );
  44287. let fb;
  44288. if ( isCube ) {
  44289. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  44290. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  44291. } else if ( isXRRenderTarget && hasExternalTextures === false ) {
  44292. fb = this._xrFramebuffer;
  44293. } else {
  44294. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  44295. fb = renderTargetContextData.framebuffers[ cacheKey ];
  44296. }
  44297. if ( fb === undefined ) {
  44298. fb = gl.createFramebuffer();
  44299. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44300. const textures = descriptor.textures;
  44301. if ( isCube ) {
  44302. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  44303. const { textureGPU } = this.get( textures[ 0 ] );
  44304. const cubeFace = this.renderer._activeCubeFace;
  44305. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  44306. } else {
  44307. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  44308. for ( let i = 0; i < textures.length; i ++ ) {
  44309. const texture = textures[ i ];
  44310. const textureData = this.get( texture );
  44311. textureData.renderTarget = descriptor.renderTarget;
  44312. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44313. const attachment = gl.COLOR_ATTACHMENT0 + i;
  44314. if ( isRenderTarget3D || isRenderTargetArray ) {
  44315. const layer = this.renderer._activeCubeFace;
  44316. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  44317. } else {
  44318. if ( renderTarget.multiview ) {
  44319. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  44320. } else if ( hasExternalTextures && useMultisampledRTT ) {
  44321. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44322. } else {
  44323. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44324. }
  44325. }
  44326. }
  44327. state.drawBuffers( descriptor, fb );
  44328. }
  44329. if ( renderTarget.isXRRenderTarget && renderTarget.autoAllocateDepthBuffer === true ) {
  44330. const renderbuffer = gl.createRenderbuffer();
  44331. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  44332. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  44333. } else {
  44334. if ( descriptor.depthTexture !== null ) {
  44335. const textureData = this.get( descriptor.depthTexture );
  44336. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44337. textureData.renderTarget = descriptor.renderTarget;
  44338. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44339. if ( renderTarget.multiview ) {
  44340. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44341. } else if ( hasExternalTextures && useMultisampledRTT ) {
  44342. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44343. } else {
  44344. if ( descriptor.depthTexture.isDepthArrayTexture ) {
  44345. const layer = this.renderer._activeCubeFace;
  44346. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  44347. } else {
  44348. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44349. }
  44350. }
  44351. }
  44352. }
  44353. } else {
  44354. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  44355. if ( isRenderCameraDepthArray ) {
  44356. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44357. const layer = this.renderer._activeCubeFace;
  44358. const depthData = this.get( descriptor.depthTexture );
  44359. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44360. gl.framebufferTextureLayer(
  44361. gl.FRAMEBUFFER,
  44362. depthStyle,
  44363. depthData.textureGPU,
  44364. 0,
  44365. layer
  44366. );
  44367. }
  44368. // rebind external XR textures
  44369. if ( ( isXRRenderTarget && hasExternalTextures ) || renderTarget.multiview ) {
  44370. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44371. // rebind color
  44372. const textureData = this.get( descriptor.textures[ 0 ] );
  44373. if ( renderTarget.multiview ) {
  44374. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  44375. } else if ( useMultisampledRTT ) {
  44376. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44377. } else {
  44378. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44379. }
  44380. // rebind depth
  44381. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44382. if ( renderTarget.autoAllocateDepthBuffer === true ) {
  44383. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  44384. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44385. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  44386. } else {
  44387. const textureData = this.get( descriptor.depthTexture );
  44388. if ( renderTarget.multiview ) {
  44389. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44390. } else if ( useMultisampledRTT ) {
  44391. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44392. } else {
  44393. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44394. }
  44395. }
  44396. }
  44397. }
  44398. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  44399. if ( msaaFb === undefined ) {
  44400. const invalidationArray = [];
  44401. msaaFb = gl.createFramebuffer();
  44402. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  44403. const msaaRenderbuffers = [];
  44404. const textures = descriptor.textures;
  44405. for ( let i = 0; i < textures.length; i ++ ) {
  44406. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  44407. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44408. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  44409. if ( depthBuffer ) {
  44410. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44411. invalidationArray.push( depthStyle );
  44412. }
  44413. const texture = descriptor.textures[ i ];
  44414. const textureData = this.get( texture );
  44415. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  44416. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44417. }
  44418. renderTargetContextData.msaaFrameBuffer = msaaFb;
  44419. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  44420. if ( depthRenderbuffer === undefined ) {
  44421. depthRenderbuffer = gl.createRenderbuffer();
  44422. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  44423. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  44424. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44425. invalidationArray.push( depthStyle );
  44426. }
  44427. renderTargetContextData.invalidationArray = invalidationArray;
  44428. }
  44429. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44430. } else {
  44431. currentFrameBuffer = fb;
  44432. }
  44433. }
  44434. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  44435. }
  44436. /**
  44437. * Computes the VAO key for the given index and attributes.
  44438. *
  44439. * @private
  44440. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  44441. * @return {string} The VAO key.
  44442. */
  44443. _getVaoKey( attributes ) {
  44444. let key = '';
  44445. for ( let i = 0; i < attributes.length; i ++ ) {
  44446. const attributeData = this.get( attributes[ i ] );
  44447. key += ':' + attributeData.id;
  44448. }
  44449. return key;
  44450. }
  44451. /**
  44452. * Creates a VAO from the index and attributes.
  44453. *
  44454. * @private
  44455. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  44456. * @return {Object} The VAO data.
  44457. */
  44458. _createVao( attributes ) {
  44459. const { gl } = this;
  44460. const vaoGPU = gl.createVertexArray();
  44461. let key = '';
  44462. let staticVao = true;
  44463. gl.bindVertexArray( vaoGPU );
  44464. for ( let i = 0; i < attributes.length; i ++ ) {
  44465. const attribute = attributes[ i ];
  44466. const attributeData = this.get( attribute );
  44467. key += ':' + attributeData.id;
  44468. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  44469. gl.enableVertexAttribArray( i );
  44470. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  44471. let stride, offset;
  44472. if ( attribute.isInterleavedBufferAttribute === true ) {
  44473. stride = attribute.data.stride * attributeData.bytesPerElement;
  44474. offset = attribute.offset * attributeData.bytesPerElement;
  44475. } else {
  44476. stride = 0;
  44477. offset = 0;
  44478. }
  44479. if ( attributeData.isInteger ) {
  44480. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  44481. } else {
  44482. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  44483. }
  44484. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  44485. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  44486. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  44487. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  44488. }
  44489. }
  44490. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  44491. this.vaoCache[ key ] = vaoGPU;
  44492. return { vaoGPU, staticVao };
  44493. }
  44494. /**
  44495. * Creates a transform feedback from the given transform buffers.
  44496. *
  44497. * @private
  44498. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  44499. * @return {WebGLTransformFeedback} The transform feedback.
  44500. */
  44501. _getTransformFeedback( transformBuffers ) {
  44502. let key = '';
  44503. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44504. key += ':' + transformBuffers[ i ].id;
  44505. }
  44506. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  44507. if ( transformFeedbackGPU !== undefined ) {
  44508. return transformFeedbackGPU;
  44509. }
  44510. const { gl } = this;
  44511. transformFeedbackGPU = gl.createTransformFeedback();
  44512. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  44513. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44514. const attributeData = transformBuffers[ i ];
  44515. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  44516. }
  44517. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  44518. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  44519. return transformFeedbackGPU;
  44520. }
  44521. /**
  44522. * Setups the given bindings.
  44523. *
  44524. * @private
  44525. * @param {Array<BindGroup>} bindings - The bindings.
  44526. * @param {WebGLProgram} programGPU - The WebGL program.
  44527. */
  44528. _setupBindings( bindings, programGPU ) {
  44529. const gl = this.gl;
  44530. for ( const bindGroup of bindings ) {
  44531. for ( const binding of bindGroup.bindings ) {
  44532. const bindingData = this.get( binding );
  44533. const index = bindingData.index;
  44534. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44535. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  44536. gl.uniformBlockBinding( programGPU, location, index );
  44537. } else if ( binding.isSampledTexture ) {
  44538. const location = gl.getUniformLocation( programGPU, binding.name );
  44539. gl.uniform1i( location, index );
  44540. }
  44541. }
  44542. }
  44543. }
  44544. /**
  44545. * Binds the given uniforms.
  44546. *
  44547. * @private
  44548. * @param {Array<BindGroup>} bindings - The bindings.
  44549. */
  44550. _bindUniforms( bindings ) {
  44551. const { gl, state } = this;
  44552. for ( const bindGroup of bindings ) {
  44553. for ( const binding of bindGroup.bindings ) {
  44554. const bindingData = this.get( binding );
  44555. const index = bindingData.index;
  44556. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44557. // TODO USE bindBufferRange to group multiple uniform buffers
  44558. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  44559. } else if ( binding.isSampledTexture ) {
  44560. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  44561. }
  44562. }
  44563. }
  44564. }
  44565. /**
  44566. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  44567. * should be used when MSAA is enabled.
  44568. *
  44569. * @private
  44570. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  44571. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  44572. */
  44573. _useMultisampledExtension( renderTarget ) {
  44574. if ( renderTarget.multiview === true ) {
  44575. return true;
  44576. }
  44577. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget.autoAllocateDepthBuffer !== false;
  44578. }
  44579. /**
  44580. * Frees internal resources.
  44581. */
  44582. dispose() {
  44583. const extension = this.extensions.get( 'WEBGL_lose_context' );
  44584. if ( extension ) extension.loseContext();
  44585. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  44586. }
  44587. }
  44588. const GPUPrimitiveTopology = {
  44589. PointList: 'point-list',
  44590. LineList: 'line-list',
  44591. LineStrip: 'line-strip',
  44592. TriangleList: 'triangle-list',
  44593. TriangleStrip: 'triangle-strip',
  44594. };
  44595. const GPUCompareFunction = {
  44596. Never: 'never',
  44597. Less: 'less',
  44598. Equal: 'equal',
  44599. LessEqual: 'less-equal',
  44600. Greater: 'greater',
  44601. NotEqual: 'not-equal',
  44602. GreaterEqual: 'greater-equal',
  44603. Always: 'always'
  44604. };
  44605. const GPUStoreOp = {
  44606. Store: 'store'};
  44607. const GPULoadOp = {
  44608. Load: 'load',
  44609. Clear: 'clear'
  44610. };
  44611. const GPUFrontFace = {
  44612. CCW: 'ccw'};
  44613. const GPUCullMode = {
  44614. None: 'none',
  44615. Front: 'front',
  44616. Back: 'back'
  44617. };
  44618. const GPUIndexFormat = {
  44619. Uint16: 'uint16',
  44620. Uint32: 'uint32'
  44621. };
  44622. const GPUTextureFormat = {
  44623. // 8-bit formats
  44624. R8Unorm: 'r8unorm',
  44625. R8Snorm: 'r8snorm',
  44626. R8Uint: 'r8uint',
  44627. R8Sint: 'r8sint',
  44628. // 16-bit formats
  44629. R16Uint: 'r16uint',
  44630. R16Sint: 'r16sint',
  44631. R16Float: 'r16float',
  44632. RG8Unorm: 'rg8unorm',
  44633. RG8Snorm: 'rg8snorm',
  44634. RG8Uint: 'rg8uint',
  44635. RG8Sint: 'rg8sint',
  44636. // 32-bit formats
  44637. R32Uint: 'r32uint',
  44638. R32Sint: 'r32sint',
  44639. R32Float: 'r32float',
  44640. RG16Uint: 'rg16uint',
  44641. RG16Sint: 'rg16sint',
  44642. RG16Float: 'rg16float',
  44643. RGBA8Unorm: 'rgba8unorm',
  44644. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  44645. RGBA8Snorm: 'rgba8snorm',
  44646. RGBA8Uint: 'rgba8uint',
  44647. RGBA8Sint: 'rgba8sint',
  44648. BGRA8Unorm: 'bgra8unorm',
  44649. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  44650. // Packed 32-bit formats
  44651. RGB9E5UFloat: 'rgb9e5ufloat',
  44652. RGB10A2Unorm: 'rgb10a2unorm',
  44653. RG11B10UFloat: 'rgb10a2unorm',
  44654. // 64-bit formats
  44655. RG32Uint: 'rg32uint',
  44656. RG32Sint: 'rg32sint',
  44657. RG32Float: 'rg32float',
  44658. RGBA16Uint: 'rgba16uint',
  44659. RGBA16Sint: 'rgba16sint',
  44660. RGBA16Float: 'rgba16float',
  44661. // 128-bit formats
  44662. RGBA32Uint: 'rgba32uint',
  44663. RGBA32Sint: 'rgba32sint',
  44664. RGBA32Float: 'rgba32float',
  44665. Depth16Unorm: 'depth16unorm',
  44666. Depth24Plus: 'depth24plus',
  44667. Depth24PlusStencil8: 'depth24plus-stencil8',
  44668. Depth32Float: 'depth32float',
  44669. // 'depth32float-stencil8' extension
  44670. Depth32FloatStencil8: 'depth32float-stencil8',
  44671. // BC compressed formats usable if 'texture-compression-bc' is both
  44672. // supported by the device/user agent and enabled in requestDevice.
  44673. BC1RGBAUnorm: 'bc1-rgba-unorm',
  44674. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  44675. BC2RGBAUnorm: 'bc2-rgba-unorm',
  44676. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  44677. BC3RGBAUnorm: 'bc3-rgba-unorm',
  44678. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  44679. BC4RUnorm: 'bc4-r-unorm',
  44680. BC4RSnorm: 'bc4-r-snorm',
  44681. BC5RGUnorm: 'bc5-rg-unorm',
  44682. BC5RGSnorm: 'bc5-rg-snorm',
  44683. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  44684. BC6HRGBFloat: 'bc6h-rgb-float',
  44685. BC7RGBAUnorm: 'bc7-rgba-unorm',
  44686. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  44687. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  44688. // supported by the device/user agent and enabled in requestDevice.
  44689. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  44690. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  44691. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  44692. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  44693. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  44694. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  44695. EACR11Unorm: 'eac-r11unorm',
  44696. EACR11Snorm: 'eac-r11snorm',
  44697. EACRG11Unorm: 'eac-rg11unorm',
  44698. EACRG11Snorm: 'eac-rg11snorm',
  44699. // ASTC compressed formats usable if 'texture-compression-astc' is both
  44700. // supported by the device/user agent and enabled in requestDevice.
  44701. ASTC4x4Unorm: 'astc-4x4-unorm',
  44702. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  44703. ASTC5x4Unorm: 'astc-5x4-unorm',
  44704. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  44705. ASTC5x5Unorm: 'astc-5x5-unorm',
  44706. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  44707. ASTC6x5Unorm: 'astc-6x5-unorm',
  44708. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  44709. ASTC6x6Unorm: 'astc-6x6-unorm',
  44710. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  44711. ASTC8x5Unorm: 'astc-8x5-unorm',
  44712. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  44713. ASTC8x6Unorm: 'astc-8x6-unorm',
  44714. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  44715. ASTC8x8Unorm: 'astc-8x8-unorm',
  44716. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  44717. ASTC10x5Unorm: 'astc-10x5-unorm',
  44718. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  44719. ASTC10x6Unorm: 'astc-10x6-unorm',
  44720. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  44721. ASTC10x8Unorm: 'astc-10x8-unorm',
  44722. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  44723. ASTC10x10Unorm: 'astc-10x10-unorm',
  44724. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  44725. ASTC12x10Unorm: 'astc-12x10-unorm',
  44726. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  44727. ASTC12x12Unorm: 'astc-12x12-unorm',
  44728. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  44729. };
  44730. const GPUAddressMode = {
  44731. ClampToEdge: 'clamp-to-edge',
  44732. Repeat: 'repeat',
  44733. MirrorRepeat: 'mirror-repeat'
  44734. };
  44735. const GPUFilterMode = {
  44736. Linear: 'linear',
  44737. Nearest: 'nearest'
  44738. };
  44739. const GPUBlendFactor = {
  44740. Zero: 'zero',
  44741. One: 'one',
  44742. Src: 'src',
  44743. OneMinusSrc: 'one-minus-src',
  44744. SrcAlpha: 'src-alpha',
  44745. OneMinusSrcAlpha: 'one-minus-src-alpha',
  44746. Dst: 'dst',
  44747. OneMinusDstColor: 'one-minus-dst',
  44748. DstAlpha: 'dst-alpha',
  44749. OneMinusDstAlpha: 'one-minus-dst-alpha',
  44750. SrcAlphaSaturated: 'src-alpha-saturated',
  44751. Constant: 'constant',
  44752. OneMinusConstant: 'one-minus-constant'
  44753. };
  44754. const GPUBlendOperation = {
  44755. Add: 'add',
  44756. Subtract: 'subtract',
  44757. ReverseSubtract: 'reverse-subtract',
  44758. Min: 'min',
  44759. Max: 'max'
  44760. };
  44761. const GPUColorWriteFlags = {
  44762. None: 0,
  44763. All: 0xF
  44764. };
  44765. const GPUStencilOperation = {
  44766. Keep: 'keep',
  44767. Zero: 'zero',
  44768. Replace: 'replace',
  44769. Invert: 'invert',
  44770. IncrementClamp: 'increment-clamp',
  44771. DecrementClamp: 'decrement-clamp',
  44772. IncrementWrap: 'increment-wrap',
  44773. DecrementWrap: 'decrement-wrap'
  44774. };
  44775. const GPUBufferBindingType = {
  44776. Storage: 'storage',
  44777. ReadOnlyStorage: 'read-only-storage'
  44778. };
  44779. const GPUStorageTextureAccess = {
  44780. WriteOnly: 'write-only',
  44781. ReadOnly: 'read-only',
  44782. ReadWrite: 'read-write',
  44783. };
  44784. const GPUSamplerBindingType = {
  44785. NonFiltering: 'non-filtering',
  44786. Comparison: 'comparison'
  44787. };
  44788. const GPUTextureSampleType = {
  44789. Float: 'float',
  44790. UnfilterableFloat: 'unfilterable-float',
  44791. Depth: 'depth',
  44792. SInt: 'sint',
  44793. UInt: 'uint'
  44794. };
  44795. const GPUTextureDimension = {
  44796. TwoD: '2d',
  44797. ThreeD: '3d'
  44798. };
  44799. const GPUTextureViewDimension = {
  44800. TwoD: '2d',
  44801. TwoDArray: '2d-array',
  44802. Cube: 'cube',
  44803. ThreeD: '3d'
  44804. };
  44805. const GPUTextureAspect = {
  44806. All: 'all'};
  44807. const GPUInputStepMode = {
  44808. Vertex: 'vertex',
  44809. Instance: 'instance'
  44810. };
  44811. const GPUFeatureName = {
  44812. DepthClipControl: 'depth-clip-control',
  44813. Depth32FloatStencil8: 'depth32float-stencil8',
  44814. TextureCompressionBC: 'texture-compression-bc',
  44815. TextureCompressionETC2: 'texture-compression-etc2',
  44816. TextureCompressionASTC: 'texture-compression-astc',
  44817. TimestampQuery: 'timestamp-query',
  44818. IndirectFirstInstance: 'indirect-first-instance',
  44819. ShaderF16: 'shader-f16',
  44820. RG11B10UFloat: 'rg11b10ufloat-renderable',
  44821. BGRA8UNormStorage: 'bgra8unorm-storage',
  44822. Float32Filterable: 'float32-filterable',
  44823. ClipDistances: 'clip-distances',
  44824. DualSourceBlending: 'dual-source-blending',
  44825. Subgroups: 'subgroups'
  44826. };
  44827. /**
  44828. * Represents a sampler binding type.
  44829. *
  44830. * @private
  44831. * @augments Binding
  44832. */
  44833. class Sampler extends Binding {
  44834. /**
  44835. * Constructs a new sampler.
  44836. *
  44837. * @param {string} name - The samplers's name.
  44838. * @param {?Texture} texture - The texture this binding is referring to.
  44839. */
  44840. constructor( name, texture ) {
  44841. super( name );
  44842. /**
  44843. * The texture the sampler is referring to.
  44844. *
  44845. * @type {?Texture}
  44846. */
  44847. this.texture = texture;
  44848. /**
  44849. * The binding's version.
  44850. *
  44851. * @type {number}
  44852. */
  44853. this.version = texture ? texture.version : 0;
  44854. /**
  44855. * This flag can be used for type testing.
  44856. *
  44857. * @type {boolean}
  44858. * @readonly
  44859. * @default true
  44860. */
  44861. this.isSampler = true;
  44862. }
  44863. }
  44864. /**
  44865. * A special form of sampler binding type.
  44866. * It's texture value is managed by a node object.
  44867. *
  44868. * @private
  44869. * @augments Sampler
  44870. */
  44871. class NodeSampler extends Sampler {
  44872. /**
  44873. * Constructs a new node-based sampler.
  44874. *
  44875. * @param {string} name - The samplers's name.
  44876. * @param {TextureNode} textureNode - The texture node.
  44877. * @param {UniformGroupNode} groupNode - The uniform group node.
  44878. */
  44879. constructor( name, textureNode, groupNode ) {
  44880. super( name, textureNode ? textureNode.value : null );
  44881. /**
  44882. * The texture node.
  44883. *
  44884. * @type {TextureNode}
  44885. */
  44886. this.textureNode = textureNode;
  44887. /**
  44888. * The uniform group node.
  44889. *
  44890. * @type {UniformGroupNode}
  44891. */
  44892. this.groupNode = groupNode;
  44893. }
  44894. /**
  44895. * Updates the texture value of this sampler.
  44896. */
  44897. update() {
  44898. this.texture = this.textureNode.value;
  44899. }
  44900. }
  44901. /**
  44902. * Represents a storage buffer binding type.
  44903. *
  44904. * @private
  44905. * @augments Buffer
  44906. */
  44907. class StorageBuffer extends Buffer {
  44908. /**
  44909. * Constructs a new uniform buffer.
  44910. *
  44911. * @param {string} name - The buffer's name.
  44912. * @param {BufferAttribute} attribute - The buffer attribute.
  44913. */
  44914. constructor( name, attribute ) {
  44915. super( name, attribute ? attribute.array : null );
  44916. /**
  44917. * This flag can be used for type testing.
  44918. *
  44919. * @type {BufferAttribute}
  44920. */
  44921. this.attribute = attribute;
  44922. /**
  44923. * This flag can be used for type testing.
  44924. *
  44925. * @type {boolean}
  44926. * @readonly
  44927. * @default true
  44928. */
  44929. this.isStorageBuffer = true;
  44930. }
  44931. }
  44932. let _id = 0;
  44933. /**
  44934. * A special form of storage buffer binding type.
  44935. * It's buffer value is managed by a node object.
  44936. *
  44937. * @private
  44938. * @augments StorageBuffer
  44939. */
  44940. class NodeStorageBuffer extends StorageBuffer {
  44941. /**
  44942. * Constructs a new node-based storage buffer.
  44943. *
  44944. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  44945. * @param {UniformGroupNode} groupNode - The uniform group node.
  44946. */
  44947. constructor( nodeUniform, groupNode ) {
  44948. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  44949. /**
  44950. * The node uniform.
  44951. *
  44952. * @type {StorageBufferNode}
  44953. */
  44954. this.nodeUniform = nodeUniform;
  44955. /**
  44956. * The access type.
  44957. *
  44958. * @type {string}
  44959. */
  44960. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  44961. /**
  44962. * The uniform group node.
  44963. *
  44964. * @type {UniformGroupNode}
  44965. */
  44966. this.groupNode = groupNode;
  44967. }
  44968. /**
  44969. * The storage buffer.
  44970. *
  44971. * @type {BufferAttribute}
  44972. */
  44973. get buffer() {
  44974. return this.nodeUniform.value;
  44975. }
  44976. }
  44977. /**
  44978. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  44979. *
  44980. * @private
  44981. */
  44982. class WebGPUTexturePassUtils extends DataMap {
  44983. /**
  44984. * Constructs a new utility object.
  44985. *
  44986. * @param {GPUDevice} device - The WebGPU device.
  44987. */
  44988. constructor( device ) {
  44989. super();
  44990. /**
  44991. * The WebGPU device.
  44992. *
  44993. * @type {GPUDevice}
  44994. */
  44995. this.device = device;
  44996. const mipmapVertexSource = `
  44997. struct VarysStruct {
  44998. @builtin( position ) Position: vec4<f32>,
  44999. @location( 0 ) vTex : vec2<f32>
  45000. };
  45001. @vertex
  45002. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  45003. var Varys : VarysStruct;
  45004. var pos = array< vec2<f32>, 4 >(
  45005. vec2<f32>( -1.0, 1.0 ),
  45006. vec2<f32>( 1.0, 1.0 ),
  45007. vec2<f32>( -1.0, -1.0 ),
  45008. vec2<f32>( 1.0, -1.0 )
  45009. );
  45010. var tex = array< vec2<f32>, 4 >(
  45011. vec2<f32>( 0.0, 0.0 ),
  45012. vec2<f32>( 1.0, 0.0 ),
  45013. vec2<f32>( 0.0, 1.0 ),
  45014. vec2<f32>( 1.0, 1.0 )
  45015. );
  45016. Varys.vTex = tex[ vertexIndex ];
  45017. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  45018. return Varys;
  45019. }
  45020. `;
  45021. const mipmapFragmentSource = `
  45022. @group( 0 ) @binding( 0 )
  45023. var imgSampler : sampler;
  45024. @group( 0 ) @binding( 1 )
  45025. var img : texture_2d<f32>;
  45026. @fragment
  45027. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45028. return textureSample( img, imgSampler, vTex );
  45029. }
  45030. `;
  45031. const flipYFragmentSource = `
  45032. @group( 0 ) @binding( 0 )
  45033. var imgSampler : sampler;
  45034. @group( 0 ) @binding( 1 )
  45035. var img : texture_2d<f32>;
  45036. @fragment
  45037. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45038. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  45039. }
  45040. `;
  45041. /**
  45042. * The mipmap GPU sampler.
  45043. *
  45044. * @type {GPUSampler}
  45045. */
  45046. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  45047. /**
  45048. * The flipY GPU sampler.
  45049. *
  45050. * @type {GPUSampler}
  45051. */
  45052. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  45053. /**
  45054. * A cache for GPU render pipelines used for copy/transfer passes.
  45055. * Every texture format requires a unique pipeline.
  45056. *
  45057. * @type {Object<string,GPURenderPipeline>}
  45058. */
  45059. this.transferPipelines = {};
  45060. /**
  45061. * A cache for GPU render pipelines used for flipY passes.
  45062. * Every texture format requires a unique pipeline.
  45063. *
  45064. * @type {Object<string,GPURenderPipeline>}
  45065. */
  45066. this.flipYPipelines = {};
  45067. /**
  45068. * The mipmap vertex shader module.
  45069. *
  45070. * @type {GPUShaderModule}
  45071. */
  45072. this.mipmapVertexShaderModule = device.createShaderModule( {
  45073. label: 'mipmapVertex',
  45074. code: mipmapVertexSource
  45075. } );
  45076. /**
  45077. * The mipmap fragment shader module.
  45078. *
  45079. * @type {GPUShaderModule}
  45080. */
  45081. this.mipmapFragmentShaderModule = device.createShaderModule( {
  45082. label: 'mipmapFragment',
  45083. code: mipmapFragmentSource
  45084. } );
  45085. /**
  45086. * The flipY fragment shader module.
  45087. *
  45088. * @type {GPUShaderModule}
  45089. */
  45090. this.flipYFragmentShaderModule = device.createShaderModule( {
  45091. label: 'flipYFragment',
  45092. code: flipYFragmentSource
  45093. } );
  45094. }
  45095. /**
  45096. * Returns a render pipeline for the internal copy render pass. The pass
  45097. * requires a unique render pipeline for each texture format.
  45098. *
  45099. * @param {string} format - The GPU texture format
  45100. * @return {GPURenderPipeline} The GPU render pipeline.
  45101. */
  45102. getTransferPipeline( format ) {
  45103. let pipeline = this.transferPipelines[ format ];
  45104. if ( pipeline === undefined ) {
  45105. pipeline = this.device.createRenderPipeline( {
  45106. label: `mipmap-${ format }`,
  45107. vertex: {
  45108. module: this.mipmapVertexShaderModule,
  45109. entryPoint: 'main'
  45110. },
  45111. fragment: {
  45112. module: this.mipmapFragmentShaderModule,
  45113. entryPoint: 'main',
  45114. targets: [ { format } ]
  45115. },
  45116. primitive: {
  45117. topology: GPUPrimitiveTopology.TriangleStrip,
  45118. stripIndexFormat: GPUIndexFormat.Uint32
  45119. },
  45120. layout: 'auto'
  45121. } );
  45122. this.transferPipelines[ format ] = pipeline;
  45123. }
  45124. return pipeline;
  45125. }
  45126. /**
  45127. * Returns a render pipeline for the flipY render pass. The pass
  45128. * requires a unique render pipeline for each texture format.
  45129. *
  45130. * @param {string} format - The GPU texture format
  45131. * @return {GPURenderPipeline} The GPU render pipeline.
  45132. */
  45133. getFlipYPipeline( format ) {
  45134. let pipeline = this.flipYPipelines[ format ];
  45135. if ( pipeline === undefined ) {
  45136. pipeline = this.device.createRenderPipeline( {
  45137. label: `flipY-${ format }`,
  45138. vertex: {
  45139. module: this.mipmapVertexShaderModule,
  45140. entryPoint: 'main'
  45141. },
  45142. fragment: {
  45143. module: this.flipYFragmentShaderModule,
  45144. entryPoint: 'main',
  45145. targets: [ { format } ]
  45146. },
  45147. primitive: {
  45148. topology: GPUPrimitiveTopology.TriangleStrip,
  45149. stripIndexFormat: GPUIndexFormat.Uint32
  45150. },
  45151. layout: 'auto'
  45152. } );
  45153. this.flipYPipelines[ format ] = pipeline;
  45154. }
  45155. return pipeline;
  45156. }
  45157. /**
  45158. * Flip the contents of the given GPU texture along its vertical axis.
  45159. *
  45160. * @param {GPUTexture} textureGPU - The GPU texture object.
  45161. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45162. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45163. */
  45164. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45165. const format = textureGPUDescriptor.format;
  45166. const { width, height } = textureGPUDescriptor.size;
  45167. const transferPipeline = this.getTransferPipeline( format );
  45168. const flipYPipeline = this.getFlipYPipeline( format );
  45169. const tempTexture = this.device.createTexture( {
  45170. size: { width, height, depthOrArrayLayers: 1 },
  45171. format,
  45172. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  45173. } );
  45174. const srcView = textureGPU.createView( {
  45175. baseMipLevel: 0,
  45176. mipLevelCount: 1,
  45177. dimension: GPUTextureViewDimension.TwoD,
  45178. baseArrayLayer
  45179. } );
  45180. const dstView = tempTexture.createView( {
  45181. baseMipLevel: 0,
  45182. mipLevelCount: 1,
  45183. dimension: GPUTextureViewDimension.TwoD,
  45184. baseArrayLayer: 0
  45185. } );
  45186. const commandEncoder = this.device.createCommandEncoder( {} );
  45187. const pass = ( pipeline, sourceView, destinationView ) => {
  45188. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45189. const bindGroup = this.device.createBindGroup( {
  45190. layout: bindGroupLayout,
  45191. entries: [ {
  45192. binding: 0,
  45193. resource: this.flipYSampler
  45194. }, {
  45195. binding: 1,
  45196. resource: sourceView
  45197. } ]
  45198. } );
  45199. const passEncoder = commandEncoder.beginRenderPass( {
  45200. colorAttachments: [ {
  45201. view: destinationView,
  45202. loadOp: GPULoadOp.Clear,
  45203. storeOp: GPUStoreOp.Store,
  45204. clearValue: [ 0, 0, 0, 0 ]
  45205. } ]
  45206. } );
  45207. passEncoder.setPipeline( pipeline );
  45208. passEncoder.setBindGroup( 0, bindGroup );
  45209. passEncoder.draw( 4, 1, 0, 0 );
  45210. passEncoder.end();
  45211. };
  45212. pass( transferPipeline, srcView, dstView );
  45213. pass( flipYPipeline, dstView, srcView );
  45214. this.device.queue.submit( [ commandEncoder.finish() ] );
  45215. tempTexture.destroy();
  45216. }
  45217. /**
  45218. * Generates mipmaps for the given GPU texture.
  45219. *
  45220. * @param {GPUTexture} textureGPU - The GPU texture object.
  45221. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45222. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45223. */
  45224. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45225. const textureData = this.get( textureGPU );
  45226. if ( textureData.useCount === undefined ) {
  45227. textureData.useCount = 0;
  45228. textureData.layers = [];
  45229. }
  45230. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  45231. const commandEncoder = this.device.createCommandEncoder( {} );
  45232. this._mipmapRunBundles( commandEncoder, passes );
  45233. this.device.queue.submit( [ commandEncoder.finish() ] );
  45234. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  45235. textureData.useCount ++;
  45236. }
  45237. /**
  45238. * Since multiple copy render passes are required to generate mipmaps, the passes
  45239. * are managed as render bundles to improve performance.
  45240. *
  45241. * @param {GPUTexture} textureGPU - The GPU texture object.
  45242. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45243. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  45244. * @return {Array<Object>} An array of render bundles.
  45245. */
  45246. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  45247. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  45248. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45249. let srcView = textureGPU.createView( {
  45250. baseMipLevel: 0,
  45251. mipLevelCount: 1,
  45252. dimension: GPUTextureViewDimension.TwoD,
  45253. baseArrayLayer
  45254. } );
  45255. const passes = [];
  45256. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  45257. const bindGroup = this.device.createBindGroup( {
  45258. layout: bindGroupLayout,
  45259. entries: [ {
  45260. binding: 0,
  45261. resource: this.mipmapSampler
  45262. }, {
  45263. binding: 1,
  45264. resource: srcView
  45265. } ]
  45266. } );
  45267. const dstView = textureGPU.createView( {
  45268. baseMipLevel: i,
  45269. mipLevelCount: 1,
  45270. dimension: GPUTextureViewDimension.TwoD,
  45271. baseArrayLayer
  45272. } );
  45273. const passDescriptor = {
  45274. colorAttachments: [ {
  45275. view: dstView,
  45276. loadOp: GPULoadOp.Clear,
  45277. storeOp: GPUStoreOp.Store,
  45278. clearValue: [ 0, 0, 0, 0 ]
  45279. } ]
  45280. };
  45281. const passEncoder = this.device.createRenderBundleEncoder( {
  45282. colorFormats: [ textureGPUDescriptor.format ]
  45283. } );
  45284. passEncoder.setPipeline( pipeline );
  45285. passEncoder.setBindGroup( 0, bindGroup );
  45286. passEncoder.draw( 4, 1, 0, 0 );
  45287. passes.push( {
  45288. renderBundles: [ passEncoder.finish() ],
  45289. passDescriptor
  45290. } );
  45291. srcView = dstView;
  45292. }
  45293. return passes;
  45294. }
  45295. /**
  45296. * Executes the render bundles.
  45297. *
  45298. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  45299. * @param {Array<Object>} passes - An array of render bundles.
  45300. */
  45301. _mipmapRunBundles( commandEncoder, passes ) {
  45302. const levels = passes.length;
  45303. for ( let i = 0; i < levels; i ++ ) {
  45304. const pass = passes[ i ];
  45305. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  45306. passEncoder.executeBundles( pass.renderBundles );
  45307. passEncoder.end();
  45308. }
  45309. }
  45310. }
  45311. const _compareToWebGPU = {
  45312. [ NeverCompare ]: 'never',
  45313. [ LessCompare ]: 'less',
  45314. [ EqualCompare ]: 'equal',
  45315. [ LessEqualCompare ]: 'less-equal',
  45316. [ GreaterCompare ]: 'greater',
  45317. [ GreaterEqualCompare ]: 'greater-equal',
  45318. [ AlwaysCompare ]: 'always',
  45319. [ NotEqualCompare ]: 'not-equal'
  45320. };
  45321. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  45322. /**
  45323. * A WebGPU backend utility module for managing textures.
  45324. *
  45325. * @private
  45326. */
  45327. class WebGPUTextureUtils {
  45328. /**
  45329. * Constructs a new utility object.
  45330. *
  45331. * @param {WebGPUBackend} backend - The WebGPU backend.
  45332. */
  45333. constructor( backend ) {
  45334. /**
  45335. * A reference to the WebGPU backend.
  45336. *
  45337. * @type {WebGPUBackend}
  45338. */
  45339. this.backend = backend;
  45340. /**
  45341. * A reference to the pass utils.
  45342. *
  45343. * @type {?WebGPUTexturePassUtils}
  45344. * @default null
  45345. */
  45346. this._passUtils = null;
  45347. /**
  45348. * A dictionary for managing default textures. The key
  45349. * is the texture format, the value the texture object.
  45350. *
  45351. * @type {Object<string,Texture>}
  45352. */
  45353. this.defaultTexture = {};
  45354. /**
  45355. * A dictionary for managing default cube textures. The key
  45356. * is the texture format, the value the texture object.
  45357. *
  45358. * @type {Object<string,CubeTexture>}
  45359. */
  45360. this.defaultCubeTexture = {};
  45361. /**
  45362. * A default video frame.
  45363. *
  45364. * @type {?VideoFrame}
  45365. * @default null
  45366. */
  45367. this.defaultVideoFrame = null;
  45368. /**
  45369. * Represents the color attachment of the default framebuffer.
  45370. *
  45371. * @type {?GPUTexture}
  45372. * @default null
  45373. */
  45374. this.colorBuffer = null;
  45375. /**
  45376. * Represents the depth attachment of the default framebuffer.
  45377. *
  45378. * @type {DepthTexture}
  45379. */
  45380. this.depthTexture = new DepthTexture();
  45381. this.depthTexture.name = 'depthBuffer';
  45382. }
  45383. /**
  45384. * Creates a GPU sampler for the given texture.
  45385. *
  45386. * @param {Texture} texture - The texture to create the sampler for.
  45387. */
  45388. createSampler( texture ) {
  45389. const backend = this.backend;
  45390. const device = backend.device;
  45391. const textureGPU = backend.get( texture );
  45392. const samplerDescriptorGPU = {
  45393. addressModeU: this._convertAddressMode( texture.wrapS ),
  45394. addressModeV: this._convertAddressMode( texture.wrapT ),
  45395. addressModeW: this._convertAddressMode( texture.wrapR ),
  45396. magFilter: this._convertFilterMode( texture.magFilter ),
  45397. minFilter: this._convertFilterMode( texture.minFilter ),
  45398. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  45399. maxAnisotropy: 1
  45400. };
  45401. // anisotropy can only be used when all filter modes are set to linear.
  45402. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  45403. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  45404. }
  45405. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  45406. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  45407. }
  45408. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  45409. }
  45410. /**
  45411. * Creates a default texture for the given texture that can be used
  45412. * as a placeholder until the actual texture is ready for usage.
  45413. *
  45414. * @param {Texture} texture - The texture to create a default texture for.
  45415. */
  45416. createDefaultTexture( texture ) {
  45417. let textureGPU;
  45418. const format = getFormat( texture );
  45419. if ( texture.isCubeTexture ) {
  45420. textureGPU = this._getDefaultCubeTextureGPU( format );
  45421. } else if ( texture.isVideoTexture ) {
  45422. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  45423. } else {
  45424. textureGPU = this._getDefaultTextureGPU( format );
  45425. }
  45426. this.backend.get( texture ).texture = textureGPU;
  45427. }
  45428. /**
  45429. * Defines a texture on the GPU for the given texture object.
  45430. *
  45431. * @param {Texture} texture - The texture.
  45432. * @param {Object} [options={}] - Optional configuration parameter.
  45433. */
  45434. createTexture( texture, options = {} ) {
  45435. const backend = this.backend;
  45436. const textureData = backend.get( texture );
  45437. if ( textureData.initialized ) {
  45438. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  45439. }
  45440. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  45441. if ( options.levels === undefined ) options.levels = 1;
  45442. if ( options.depth === undefined ) options.depth = 1;
  45443. const { width, height, depth, levels } = options;
  45444. if ( texture.isFramebufferTexture ) {
  45445. if ( options.renderTarget ) {
  45446. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  45447. } else {
  45448. options.format = this.backend.utils.getPreferredCanvasFormat();
  45449. }
  45450. }
  45451. const dimension = this._getDimension( texture );
  45452. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  45453. textureData.format = format;
  45454. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  45455. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  45456. if ( texture.isStorageTexture === true ) {
  45457. usage |= GPUTextureUsage.STORAGE_BINDING;
  45458. }
  45459. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  45460. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  45461. }
  45462. const textureDescriptorGPU = {
  45463. label: texture.name,
  45464. size: {
  45465. width: width,
  45466. height: height,
  45467. depthOrArrayLayers: depth,
  45468. },
  45469. mipLevelCount: levels,
  45470. sampleCount: primarySamples,
  45471. dimension: dimension,
  45472. format: format,
  45473. usage: usage
  45474. };
  45475. // texture creation
  45476. if ( texture.isVideoTexture ) {
  45477. const video = texture.source.data;
  45478. const videoFrame = new VideoFrame( video );
  45479. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  45480. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  45481. videoFrame.close();
  45482. textureData.externalTexture = video;
  45483. } else {
  45484. if ( format === undefined ) {
  45485. console.warn( 'WebGPURenderer: Texture format not supported.' );
  45486. this.createDefaultTexture( texture );
  45487. return;
  45488. }
  45489. if ( texture.isCubeTexture ) {
  45490. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  45491. }
  45492. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  45493. }
  45494. if ( isMSAA ) {
  45495. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  45496. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  45497. msaaTextureDescriptorGPU.sampleCount = samples;
  45498. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  45499. }
  45500. textureData.initialized = true;
  45501. textureData.textureDescriptorGPU = textureDescriptorGPU;
  45502. }
  45503. /**
  45504. * Destroys the GPU data for the given texture object.
  45505. *
  45506. * @param {Texture} texture - The texture.
  45507. */
  45508. destroyTexture( texture ) {
  45509. const backend = this.backend;
  45510. const textureData = backend.get( texture );
  45511. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  45512. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  45513. backend.delete( texture );
  45514. }
  45515. /**
  45516. * Destroys the GPU sampler for the given texture.
  45517. *
  45518. * @param {Texture} texture - The texture to destroy the sampler for.
  45519. */
  45520. destroySampler( texture ) {
  45521. const backend = this.backend;
  45522. const textureData = backend.get( texture );
  45523. delete textureData.sampler;
  45524. }
  45525. /**
  45526. * Generates mipmaps for the given texture.
  45527. *
  45528. * @param {Texture} texture - The texture.
  45529. */
  45530. generateMipmaps( texture ) {
  45531. const textureData = this.backend.get( texture );
  45532. if ( texture.isCubeTexture ) {
  45533. for ( let i = 0; i < 6; i ++ ) {
  45534. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  45535. }
  45536. } else {
  45537. const depth = texture.image.depth || 1;
  45538. for ( let i = 0; i < depth; i ++ ) {
  45539. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  45540. }
  45541. }
  45542. }
  45543. /**
  45544. * Returns the color buffer representing the color
  45545. * attachment of the default framebuffer.
  45546. *
  45547. * @return {GPUTexture} The color buffer.
  45548. */
  45549. getColorBuffer() {
  45550. if ( this.colorBuffer ) this.colorBuffer.destroy();
  45551. const backend = this.backend;
  45552. const { width, height } = backend.getDrawingBufferSize();
  45553. this.colorBuffer = backend.device.createTexture( {
  45554. label: 'colorBuffer',
  45555. size: {
  45556. width: width,
  45557. height: height,
  45558. depthOrArrayLayers: 1
  45559. },
  45560. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  45561. format: backend.utils.getPreferredCanvasFormat(),
  45562. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  45563. } );
  45564. return this.colorBuffer;
  45565. }
  45566. /**
  45567. * Returns the depth buffer representing the depth
  45568. * attachment of the default framebuffer.
  45569. *
  45570. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  45571. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  45572. * @return {GPUTexture} The depth buffer.
  45573. */
  45574. getDepthBuffer( depth = true, stencil = false ) {
  45575. const backend = this.backend;
  45576. const { width, height } = backend.getDrawingBufferSize();
  45577. const depthTexture = this.depthTexture;
  45578. const depthTextureGPU = backend.get( depthTexture ).texture;
  45579. let format, type;
  45580. if ( stencil ) {
  45581. format = DepthStencilFormat;
  45582. type = UnsignedInt248Type;
  45583. } else if ( depth ) {
  45584. format = DepthFormat;
  45585. type = UnsignedIntType;
  45586. }
  45587. if ( depthTextureGPU !== undefined ) {
  45588. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  45589. return depthTextureGPU;
  45590. }
  45591. this.destroyTexture( depthTexture );
  45592. }
  45593. depthTexture.name = 'depthBuffer';
  45594. depthTexture.format = format;
  45595. depthTexture.type = type;
  45596. depthTexture.image.width = width;
  45597. depthTexture.image.height = height;
  45598. this.createTexture( depthTexture, { width, height } );
  45599. return backend.get( depthTexture ).texture;
  45600. }
  45601. /**
  45602. * Uploads the updated texture data to the GPU.
  45603. *
  45604. * @param {Texture} texture - The texture.
  45605. * @param {Object} [options={}] - Optional configuration parameter.
  45606. */
  45607. updateTexture( texture, options ) {
  45608. const textureData = this.backend.get( texture );
  45609. const { textureDescriptorGPU } = textureData;
  45610. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  45611. return;
  45612. // transfer texture data
  45613. if ( texture.isDataTexture ) {
  45614. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  45615. } else if ( texture.isDataArrayTexture || texture.isDepthArrayTexture || texture.isData3DTexture ) {
  45616. for ( let i = 0; i < options.image.depth; i ++ ) {
  45617. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  45618. }
  45619. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  45620. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  45621. } else if ( texture.isCubeTexture ) {
  45622. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  45623. } else if ( texture.isVideoTexture ) {
  45624. const video = texture.source.data;
  45625. textureData.externalTexture = video;
  45626. } else {
  45627. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  45628. }
  45629. //
  45630. textureData.version = texture.version;
  45631. if ( texture.onUpdate ) texture.onUpdate( texture );
  45632. }
  45633. /**
  45634. * Returns texture data as a typed array.
  45635. *
  45636. * @async
  45637. * @param {Texture} texture - The texture to copy.
  45638. * @param {number} x - The x coordinate of the copy origin.
  45639. * @param {number} y - The y coordinate of the copy origin.
  45640. * @param {number} width - The width of the copy.
  45641. * @param {number} height - The height of the copy.
  45642. * @param {number} faceIndex - The face index.
  45643. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45644. */
  45645. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45646. const device = this.backend.device;
  45647. const textureData = this.backend.get( texture );
  45648. const textureGPU = textureData.texture;
  45649. const format = textureData.textureDescriptorGPU.format;
  45650. const bytesPerTexel = this._getBytesPerTexel( format );
  45651. let bytesPerRow = width * bytesPerTexel;
  45652. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  45653. const readBuffer = device.createBuffer(
  45654. {
  45655. size: width * height * bytesPerTexel,
  45656. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45657. }
  45658. );
  45659. const encoder = device.createCommandEncoder();
  45660. encoder.copyTextureToBuffer(
  45661. {
  45662. texture: textureGPU,
  45663. origin: { x, y, z: faceIndex },
  45664. },
  45665. {
  45666. buffer: readBuffer,
  45667. bytesPerRow: bytesPerRow
  45668. },
  45669. {
  45670. width: width,
  45671. height: height
  45672. }
  45673. );
  45674. const typedArrayType = this._getTypedArrayType( format );
  45675. device.queue.submit( [ encoder.finish() ] );
  45676. await readBuffer.mapAsync( GPUMapMode.READ );
  45677. const buffer = readBuffer.getMappedRange();
  45678. return new typedArrayType( buffer );
  45679. }
  45680. /**
  45681. * Returns `true` if the given texture is an environment map.
  45682. *
  45683. * @private
  45684. * @param {Texture} texture - The texture.
  45685. * @return {boolean} Whether the given texture is an environment map or not.
  45686. */
  45687. _isEnvironmentTexture( texture ) {
  45688. const mapping = texture.mapping;
  45689. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45690. }
  45691. /**
  45692. * Returns the default GPU texture for the given format.
  45693. *
  45694. * @private
  45695. * @param {string} format - The GPU format.
  45696. * @return {GPUTexture} The GPU texture.
  45697. */
  45698. _getDefaultTextureGPU( format ) {
  45699. let defaultTexture = this.defaultTexture[ format ];
  45700. if ( defaultTexture === undefined ) {
  45701. const texture = new Texture();
  45702. texture.minFilter = NearestFilter;
  45703. texture.magFilter = NearestFilter;
  45704. this.createTexture( texture, { width: 1, height: 1, format } );
  45705. this.defaultTexture[ format ] = defaultTexture = texture;
  45706. }
  45707. return this.backend.get( defaultTexture ).texture;
  45708. }
  45709. /**
  45710. * Returns the default GPU cube texture for the given format.
  45711. *
  45712. * @private
  45713. * @param {string} format - The GPU format.
  45714. * @return {GPUTexture} The GPU texture.
  45715. */
  45716. _getDefaultCubeTextureGPU( format ) {
  45717. let defaultCubeTexture = this.defaultTexture[ format ];
  45718. if ( defaultCubeTexture === undefined ) {
  45719. const texture = new CubeTexture();
  45720. texture.minFilter = NearestFilter;
  45721. texture.magFilter = NearestFilter;
  45722. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  45723. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  45724. }
  45725. return this.backend.get( defaultCubeTexture ).texture;
  45726. }
  45727. /**
  45728. * Returns the default video frame used as default data in context of video textures.
  45729. *
  45730. * @private
  45731. * @return {VideoFrame} The video frame.
  45732. */
  45733. _getDefaultVideoFrame() {
  45734. let defaultVideoFrame = this.defaultVideoFrame;
  45735. if ( defaultVideoFrame === null ) {
  45736. const init = {
  45737. timestamp: 0,
  45738. codedWidth: 1,
  45739. codedHeight: 1,
  45740. format: 'RGBA',
  45741. };
  45742. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  45743. }
  45744. return defaultVideoFrame;
  45745. }
  45746. /**
  45747. * Uploads cube texture image data to the GPU memory.
  45748. *
  45749. * @private
  45750. * @param {Array} images - The cube image data.
  45751. * @param {GPUTexture} textureGPU - The GPU texture.
  45752. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  45753. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  45754. */
  45755. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  45756. for ( let i = 0; i < 6; i ++ ) {
  45757. const image = images[ i ];
  45758. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  45759. if ( image.isDataTexture ) {
  45760. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  45761. } else {
  45762. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  45763. }
  45764. }
  45765. }
  45766. /**
  45767. * Uploads texture image data to the GPU memory.
  45768. *
  45769. * @private
  45770. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  45771. * @param {GPUTexture} textureGPU - The GPU texture.
  45772. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  45773. * @param {number} originDepth - The origin depth.
  45774. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  45775. */
  45776. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  45777. const device = this.backend.device;
  45778. device.queue.copyExternalImageToTexture(
  45779. {
  45780. source: image,
  45781. flipY: flipY
  45782. }, {
  45783. texture: textureGPU,
  45784. mipLevel: 0,
  45785. origin: { x: 0, y: 0, z: originDepth }
  45786. }, {
  45787. width: image.width,
  45788. height: image.height,
  45789. depthOrArrayLayers: 1
  45790. }
  45791. );
  45792. }
  45793. /**
  45794. * Returns the pass utils singleton.
  45795. *
  45796. * @private
  45797. * @return {WebGPUTexturePassUtils} The utils instance.
  45798. */
  45799. _getPassUtils() {
  45800. let passUtils = this._passUtils;
  45801. if ( passUtils === null ) {
  45802. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  45803. }
  45804. return passUtils;
  45805. }
  45806. /**
  45807. * Generates mipmaps for the given GPU texture.
  45808. *
  45809. * @private
  45810. * @param {GPUTexture} textureGPU - The GPU texture object.
  45811. * @param {Object} textureDescriptorGPU - The texture descriptor.
  45812. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45813. */
  45814. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  45815. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  45816. }
  45817. /**
  45818. * Flip the contents of the given GPU texture along its vertical axis.
  45819. *
  45820. * @private
  45821. * @param {GPUTexture} textureGPU - The GPU texture object.
  45822. * @param {Object} textureDescriptorGPU - The texture descriptor.
  45823. * @param {number} [originDepth=0] - The origin depth.
  45824. */
  45825. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  45826. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  45827. }
  45828. /**
  45829. * Uploads texture buffer data to the GPU memory.
  45830. *
  45831. * @private
  45832. * @param {Object} image - An object defining the image buffer data.
  45833. * @param {GPUTexture} textureGPU - The GPU texture.
  45834. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  45835. * @param {number} originDepth - The origin depth.
  45836. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  45837. * @param {number} [depth=0] - TODO.
  45838. */
  45839. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  45840. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  45841. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  45842. const device = this.backend.device;
  45843. const data = image.data;
  45844. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  45845. const bytesPerRow = image.width * bytesPerTexel;
  45846. device.queue.writeTexture(
  45847. {
  45848. texture: textureGPU,
  45849. mipLevel: 0,
  45850. origin: { x: 0, y: 0, z: originDepth }
  45851. },
  45852. data,
  45853. {
  45854. offset: image.width * image.height * bytesPerTexel * depth,
  45855. bytesPerRow
  45856. },
  45857. {
  45858. width: image.width,
  45859. height: image.height,
  45860. depthOrArrayLayers: 1
  45861. } );
  45862. if ( flipY === true ) {
  45863. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  45864. }
  45865. }
  45866. /**
  45867. * Uploads compressed texture data to the GPU memory.
  45868. *
  45869. * @private
  45870. * @param {Array<Object>} mipmaps - An array with mipmap data.
  45871. * @param {GPUTexture} textureGPU - The GPU texture.
  45872. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  45873. */
  45874. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  45875. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  45876. const device = this.backend.device;
  45877. const blockData = this._getBlockData( textureDescriptorGPU.format );
  45878. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  45879. for ( let i = 0; i < mipmaps.length; i ++ ) {
  45880. const mipmap = mipmaps[ i ];
  45881. const width = mipmap.width;
  45882. const height = mipmap.height;
  45883. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  45884. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  45885. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  45886. for ( let j = 0; j < depth; j ++ ) {
  45887. device.queue.writeTexture(
  45888. {
  45889. texture: textureGPU,
  45890. mipLevel: i,
  45891. origin: { x: 0, y: 0, z: j }
  45892. },
  45893. mipmap.data,
  45894. {
  45895. offset: j * bytesPerImage,
  45896. bytesPerRow,
  45897. rowsPerImage: Math.ceil( height / blockData.height )
  45898. },
  45899. {
  45900. width: Math.ceil( width / blockData.width ) * blockData.width,
  45901. height: Math.ceil( height / blockData.height ) * blockData.height,
  45902. depthOrArrayLayers: 1
  45903. }
  45904. );
  45905. }
  45906. }
  45907. }
  45908. /**
  45909. * This method is only relevant for compressed texture formats. It returns a block
  45910. * data descriptor for the given GPU compressed texture format.
  45911. *
  45912. * @private
  45913. * @param {string} format - The GPU compressed texture format.
  45914. * @return {Object} The block data descriptor.
  45915. */
  45916. _getBlockData( format ) {
  45917. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  45918. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  45919. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  45920. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  45921. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  45922. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  45923. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  45924. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  45925. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  45926. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  45927. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  45928. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  45929. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  45930. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  45931. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  45932. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  45933. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  45934. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  45935. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  45936. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  45937. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  45938. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  45939. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  45940. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  45941. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  45942. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  45943. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  45944. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  45945. }
  45946. /**
  45947. * Converts the three.js uv wrapping constants to GPU address mode constants.
  45948. *
  45949. * @private
  45950. * @param {number} value - The three.js constant defining a uv wrapping mode.
  45951. * @return {string} The GPU address mode.
  45952. */
  45953. _convertAddressMode( value ) {
  45954. let addressMode = GPUAddressMode.ClampToEdge;
  45955. if ( value === RepeatWrapping ) {
  45956. addressMode = GPUAddressMode.Repeat;
  45957. } else if ( value === MirroredRepeatWrapping ) {
  45958. addressMode = GPUAddressMode.MirrorRepeat;
  45959. }
  45960. return addressMode;
  45961. }
  45962. /**
  45963. * Converts the three.js filter constants to GPU filter constants.
  45964. *
  45965. * @private
  45966. * @param {number} value - The three.js constant defining a filter mode.
  45967. * @return {string} The GPU filter mode.
  45968. */
  45969. _convertFilterMode( value ) {
  45970. let filterMode = GPUFilterMode.Linear;
  45971. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  45972. filterMode = GPUFilterMode.Nearest;
  45973. }
  45974. return filterMode;
  45975. }
  45976. /**
  45977. * Returns the bytes-per-texel value for the given GPU texture format.
  45978. *
  45979. * @private
  45980. * @param {string} format - The GPU texture format.
  45981. * @return {number} The bytes-per-texel.
  45982. */
  45983. _getBytesPerTexel( format ) {
  45984. // 8-bit formats
  45985. if ( format === GPUTextureFormat.R8Unorm ||
  45986. format === GPUTextureFormat.R8Snorm ||
  45987. format === GPUTextureFormat.R8Uint ||
  45988. format === GPUTextureFormat.R8Sint ) return 1;
  45989. // 16-bit formats
  45990. if ( format === GPUTextureFormat.R16Uint ||
  45991. format === GPUTextureFormat.R16Sint ||
  45992. format === GPUTextureFormat.R16Float ||
  45993. format === GPUTextureFormat.RG8Unorm ||
  45994. format === GPUTextureFormat.RG8Snorm ||
  45995. format === GPUTextureFormat.RG8Uint ||
  45996. format === GPUTextureFormat.RG8Sint ) return 2;
  45997. // 32-bit formats
  45998. if ( format === GPUTextureFormat.R32Uint ||
  45999. format === GPUTextureFormat.R32Sint ||
  46000. format === GPUTextureFormat.R32Float ||
  46001. format === GPUTextureFormat.RG16Uint ||
  46002. format === GPUTextureFormat.RG16Sint ||
  46003. format === GPUTextureFormat.RG16Float ||
  46004. format === GPUTextureFormat.RGBA8Unorm ||
  46005. format === GPUTextureFormat.RGBA8UnormSRGB ||
  46006. format === GPUTextureFormat.RGBA8Snorm ||
  46007. format === GPUTextureFormat.RGBA8Uint ||
  46008. format === GPUTextureFormat.RGBA8Sint ||
  46009. format === GPUTextureFormat.BGRA8Unorm ||
  46010. format === GPUTextureFormat.BGRA8UnormSRGB ||
  46011. // Packed 32-bit formats
  46012. format === GPUTextureFormat.RGB9E5UFloat ||
  46013. format === GPUTextureFormat.RGB10A2Unorm ||
  46014. format === GPUTextureFormat.RG11B10UFloat ||
  46015. format === GPUTextureFormat.Depth32Float ||
  46016. format === GPUTextureFormat.Depth24Plus ||
  46017. format === GPUTextureFormat.Depth24PlusStencil8 ||
  46018. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  46019. // 64-bit formats
  46020. if ( format === GPUTextureFormat.RG32Uint ||
  46021. format === GPUTextureFormat.RG32Sint ||
  46022. format === GPUTextureFormat.RG32Float ||
  46023. format === GPUTextureFormat.RGBA16Uint ||
  46024. format === GPUTextureFormat.RGBA16Sint ||
  46025. format === GPUTextureFormat.RGBA16Float ) return 8;
  46026. // 128-bit formats
  46027. if ( format === GPUTextureFormat.RGBA32Uint ||
  46028. format === GPUTextureFormat.RGBA32Sint ||
  46029. format === GPUTextureFormat.RGBA32Float ) return 16;
  46030. }
  46031. /**
  46032. * Returns the corresponding typed array type for the given GPU texture format.
  46033. *
  46034. * @private
  46035. * @param {string} format - The GPU texture format.
  46036. * @return {TypedArray.constructor} The typed array type.
  46037. */
  46038. _getTypedArrayType( format ) {
  46039. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  46040. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  46041. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  46042. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  46043. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  46044. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  46045. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  46046. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  46047. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  46048. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  46049. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  46050. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  46051. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  46052. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  46053. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  46054. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  46055. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  46056. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  46057. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  46058. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  46059. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  46060. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  46061. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  46062. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  46063. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  46064. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  46065. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  46066. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  46067. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  46068. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  46069. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  46070. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  46071. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  46072. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  46073. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  46074. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  46075. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  46076. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  46077. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  46078. }
  46079. /**
  46080. * Returns the GPU dimensions for the given texture.
  46081. *
  46082. * @private
  46083. * @param {Texture} texture - The texture.
  46084. * @return {string} The GPU dimension.
  46085. */
  46086. _getDimension( texture ) {
  46087. let dimension;
  46088. if ( texture.isData3DTexture ) {
  46089. dimension = GPUTextureDimension.ThreeD;
  46090. } else {
  46091. dimension = GPUTextureDimension.TwoD;
  46092. }
  46093. return dimension;
  46094. }
  46095. }
  46096. /**
  46097. * Returns the GPU format for the given texture.
  46098. *
  46099. * @param {Texture} texture - The texture.
  46100. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  46101. * It is not necessary to apply the device for most formats.
  46102. * @return {string} The GPU format.
  46103. */
  46104. function getFormat( texture, device = null ) {
  46105. const format = texture.format;
  46106. const type = texture.type;
  46107. const colorSpace = texture.colorSpace;
  46108. let formatGPU;
  46109. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  46110. switch ( format ) {
  46111. case RGBA_S3TC_DXT1_Format:
  46112. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  46113. break;
  46114. case RGBA_S3TC_DXT3_Format:
  46115. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  46116. break;
  46117. case RGBA_S3TC_DXT5_Format:
  46118. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  46119. break;
  46120. case RGB_ETC2_Format:
  46121. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  46122. break;
  46123. case RGBA_ETC2_EAC_Format:
  46124. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  46125. break;
  46126. case RGBA_ASTC_4x4_Format:
  46127. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  46128. break;
  46129. case RGBA_ASTC_5x4_Format:
  46130. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  46131. break;
  46132. case RGBA_ASTC_5x5_Format:
  46133. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  46134. break;
  46135. case RGBA_ASTC_6x5_Format:
  46136. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  46137. break;
  46138. case RGBA_ASTC_6x6_Format:
  46139. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  46140. break;
  46141. case RGBA_ASTC_8x5_Format:
  46142. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  46143. break;
  46144. case RGBA_ASTC_8x6_Format:
  46145. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  46146. break;
  46147. case RGBA_ASTC_8x8_Format:
  46148. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  46149. break;
  46150. case RGBA_ASTC_10x5_Format:
  46151. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  46152. break;
  46153. case RGBA_ASTC_10x6_Format:
  46154. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  46155. break;
  46156. case RGBA_ASTC_10x8_Format:
  46157. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  46158. break;
  46159. case RGBA_ASTC_10x10_Format:
  46160. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  46161. break;
  46162. case RGBA_ASTC_12x10_Format:
  46163. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  46164. break;
  46165. case RGBA_ASTC_12x12_Format:
  46166. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  46167. break;
  46168. case RGBAFormat:
  46169. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46170. break;
  46171. default:
  46172. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46173. }
  46174. } else {
  46175. switch ( format ) {
  46176. case RGBAFormat:
  46177. switch ( type ) {
  46178. case ByteType:
  46179. formatGPU = GPUTextureFormat.RGBA8Snorm;
  46180. break;
  46181. case ShortType:
  46182. formatGPU = GPUTextureFormat.RGBA16Sint;
  46183. break;
  46184. case UnsignedShortType:
  46185. formatGPU = GPUTextureFormat.RGBA16Uint;
  46186. break;
  46187. case UnsignedIntType:
  46188. formatGPU = GPUTextureFormat.RGBA32Uint;
  46189. break;
  46190. case IntType:
  46191. formatGPU = GPUTextureFormat.RGBA32Sint;
  46192. break;
  46193. case UnsignedByteType:
  46194. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46195. break;
  46196. case HalfFloatType:
  46197. formatGPU = GPUTextureFormat.RGBA16Float;
  46198. break;
  46199. case FloatType:
  46200. formatGPU = GPUTextureFormat.RGBA32Float;
  46201. break;
  46202. default:
  46203. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  46204. }
  46205. break;
  46206. case RGBFormat:
  46207. switch ( type ) {
  46208. case UnsignedInt5999Type:
  46209. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  46210. break;
  46211. default:
  46212. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  46213. }
  46214. break;
  46215. case RedFormat:
  46216. switch ( type ) {
  46217. case ByteType:
  46218. formatGPU = GPUTextureFormat.R8Snorm;
  46219. break;
  46220. case ShortType:
  46221. formatGPU = GPUTextureFormat.R16Sint;
  46222. break;
  46223. case UnsignedShortType:
  46224. formatGPU = GPUTextureFormat.R16Uint;
  46225. break;
  46226. case UnsignedIntType:
  46227. formatGPU = GPUTextureFormat.R32Uint;
  46228. break;
  46229. case IntType:
  46230. formatGPU = GPUTextureFormat.R32Sint;
  46231. break;
  46232. case UnsignedByteType:
  46233. formatGPU = GPUTextureFormat.R8Unorm;
  46234. break;
  46235. case HalfFloatType:
  46236. formatGPU = GPUTextureFormat.R16Float;
  46237. break;
  46238. case FloatType:
  46239. formatGPU = GPUTextureFormat.R32Float;
  46240. break;
  46241. default:
  46242. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  46243. }
  46244. break;
  46245. case RGFormat:
  46246. switch ( type ) {
  46247. case ByteType:
  46248. formatGPU = GPUTextureFormat.RG8Snorm;
  46249. break;
  46250. case ShortType:
  46251. formatGPU = GPUTextureFormat.RG16Sint;
  46252. break;
  46253. case UnsignedShortType:
  46254. formatGPU = GPUTextureFormat.RG16Uint;
  46255. break;
  46256. case UnsignedIntType:
  46257. formatGPU = GPUTextureFormat.RG32Uint;
  46258. break;
  46259. case IntType:
  46260. formatGPU = GPUTextureFormat.RG32Sint;
  46261. break;
  46262. case UnsignedByteType:
  46263. formatGPU = GPUTextureFormat.RG8Unorm;
  46264. break;
  46265. case HalfFloatType:
  46266. formatGPU = GPUTextureFormat.RG16Float;
  46267. break;
  46268. case FloatType:
  46269. formatGPU = GPUTextureFormat.RG32Float;
  46270. break;
  46271. default:
  46272. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  46273. }
  46274. break;
  46275. case DepthFormat:
  46276. switch ( type ) {
  46277. case UnsignedShortType:
  46278. formatGPU = GPUTextureFormat.Depth16Unorm;
  46279. break;
  46280. case UnsignedIntType:
  46281. formatGPU = GPUTextureFormat.Depth24Plus;
  46282. break;
  46283. case FloatType:
  46284. formatGPU = GPUTextureFormat.Depth32Float;
  46285. break;
  46286. default:
  46287. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  46288. }
  46289. break;
  46290. case DepthStencilFormat:
  46291. switch ( type ) {
  46292. case UnsignedInt248Type:
  46293. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  46294. break;
  46295. case FloatType:
  46296. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  46297. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  46298. }
  46299. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  46300. break;
  46301. default:
  46302. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  46303. }
  46304. break;
  46305. case RedIntegerFormat:
  46306. switch ( type ) {
  46307. case IntType:
  46308. formatGPU = GPUTextureFormat.R32Sint;
  46309. break;
  46310. case UnsignedIntType:
  46311. formatGPU = GPUTextureFormat.R32Uint;
  46312. break;
  46313. default:
  46314. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  46315. }
  46316. break;
  46317. case RGIntegerFormat:
  46318. switch ( type ) {
  46319. case IntType:
  46320. formatGPU = GPUTextureFormat.RG32Sint;
  46321. break;
  46322. case UnsignedIntType:
  46323. formatGPU = GPUTextureFormat.RG32Uint;
  46324. break;
  46325. default:
  46326. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  46327. }
  46328. break;
  46329. case RGBAIntegerFormat:
  46330. switch ( type ) {
  46331. case IntType:
  46332. formatGPU = GPUTextureFormat.RGBA32Sint;
  46333. break;
  46334. case UnsignedIntType:
  46335. formatGPU = GPUTextureFormat.RGBA32Uint;
  46336. break;
  46337. default:
  46338. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  46339. }
  46340. break;
  46341. default:
  46342. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46343. }
  46344. }
  46345. return formatGPU;
  46346. }
  46347. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  46348. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  46349. const wgslTypeLib$1 = {
  46350. 'f32': 'float',
  46351. 'i32': 'int',
  46352. 'u32': 'uint',
  46353. 'bool': 'bool',
  46354. 'vec2<f32>': 'vec2',
  46355. 'vec2<i32>': 'ivec2',
  46356. 'vec2<u32>': 'uvec2',
  46357. 'vec2<bool>': 'bvec2',
  46358. 'vec2f': 'vec2',
  46359. 'vec2i': 'ivec2',
  46360. 'vec2u': 'uvec2',
  46361. 'vec2b': 'bvec2',
  46362. 'vec3<f32>': 'vec3',
  46363. 'vec3<i32>': 'ivec3',
  46364. 'vec3<u32>': 'uvec3',
  46365. 'vec3<bool>': 'bvec3',
  46366. 'vec3f': 'vec3',
  46367. 'vec3i': 'ivec3',
  46368. 'vec3u': 'uvec3',
  46369. 'vec3b': 'bvec3',
  46370. 'vec4<f32>': 'vec4',
  46371. 'vec4<i32>': 'ivec4',
  46372. 'vec4<u32>': 'uvec4',
  46373. 'vec4<bool>': 'bvec4',
  46374. 'vec4f': 'vec4',
  46375. 'vec4i': 'ivec4',
  46376. 'vec4u': 'uvec4',
  46377. 'vec4b': 'bvec4',
  46378. 'mat2x2<f32>': 'mat2',
  46379. 'mat2x2f': 'mat2',
  46380. 'mat3x3<f32>': 'mat3',
  46381. 'mat3x3f': 'mat3',
  46382. 'mat4x4<f32>': 'mat4',
  46383. 'mat4x4f': 'mat4',
  46384. 'sampler': 'sampler',
  46385. 'texture_1d': 'texture',
  46386. 'texture_2d': 'texture',
  46387. 'texture_2d_array': 'texture',
  46388. 'texture_multisampled_2d': 'cubeTexture',
  46389. 'texture_depth_2d': 'depthTexture',
  46390. 'texture_depth_2d_array': 'depthTexture',
  46391. 'texture_depth_multisampled_2d': 'depthTexture',
  46392. 'texture_depth_cube': 'depthTexture',
  46393. 'texture_depth_cube_array': 'depthTexture',
  46394. 'texture_3d': 'texture3D',
  46395. 'texture_cube': 'cubeTexture',
  46396. 'texture_cube_array': 'cubeTexture',
  46397. 'texture_storage_1d': 'storageTexture',
  46398. 'texture_storage_2d': 'storageTexture',
  46399. 'texture_storage_2d_array': 'storageTexture',
  46400. 'texture_storage_3d': 'storageTexture'
  46401. };
  46402. const parse = ( source ) => {
  46403. source = source.trim();
  46404. const declaration = source.match( declarationRegexp );
  46405. if ( declaration !== null && declaration.length === 4 ) {
  46406. const inputsCode = declaration[ 2 ];
  46407. const propsMatches = [];
  46408. let match = null;
  46409. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  46410. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  46411. }
  46412. // Process matches to correctly pair names and types
  46413. const inputs = [];
  46414. for ( let i = 0; i < propsMatches.length; i ++ ) {
  46415. const { name, type } = propsMatches[ i ];
  46416. let resolvedType = type;
  46417. if ( resolvedType.startsWith( 'ptr' ) ) {
  46418. resolvedType = 'pointer';
  46419. } else {
  46420. if ( resolvedType.startsWith( 'texture' ) ) {
  46421. resolvedType = type.split( '<' )[ 0 ];
  46422. }
  46423. resolvedType = wgslTypeLib$1[ resolvedType ];
  46424. }
  46425. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  46426. }
  46427. const blockCode = source.substring( declaration[ 0 ].length );
  46428. const outputType = declaration[ 3 ] || 'void';
  46429. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  46430. const type = wgslTypeLib$1[ outputType ] || outputType;
  46431. return {
  46432. type,
  46433. inputs,
  46434. name,
  46435. inputsCode,
  46436. blockCode,
  46437. outputType
  46438. };
  46439. } else {
  46440. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  46441. }
  46442. };
  46443. /**
  46444. * This class represents a WSL node function.
  46445. *
  46446. * @augments NodeFunction
  46447. */
  46448. class WGSLNodeFunction extends NodeFunction {
  46449. /**
  46450. * Constructs a new WGSL node function.
  46451. *
  46452. * @param {string} source - The WGSL source.
  46453. */
  46454. constructor( source ) {
  46455. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  46456. super( type, inputs, name );
  46457. this.inputsCode = inputsCode;
  46458. this.blockCode = blockCode;
  46459. this.outputType = outputType;
  46460. }
  46461. /**
  46462. * This method returns the WGSL code of the node function.
  46463. *
  46464. * @param {string} [name=this.name] - The function's name.
  46465. * @return {string} The shader code.
  46466. */
  46467. getCode( name = this.name ) {
  46468. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  46469. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  46470. }
  46471. }
  46472. /**
  46473. * A WGSL node parser.
  46474. *
  46475. * @augments NodeParser
  46476. */
  46477. class WGSLNodeParser extends NodeParser {
  46478. /**
  46479. * The method parses the given WGSL code an returns a node function.
  46480. *
  46481. * @param {string} source - The WGSL code.
  46482. * @return {WGSLNodeFunction} A node function.
  46483. */
  46484. parseFunction( source ) {
  46485. return new WGSLNodeFunction( source );
  46486. }
  46487. }
  46488. // GPUShaderStage is not defined in browsers not supporting WebGPU
  46489. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  46490. const accessNames = {
  46491. [ NodeAccess.READ_ONLY ]: 'read',
  46492. [ NodeAccess.WRITE_ONLY ]: 'write',
  46493. [ NodeAccess.READ_WRITE ]: 'read_write'
  46494. };
  46495. const wrapNames = {
  46496. [ RepeatWrapping ]: 'repeat',
  46497. [ ClampToEdgeWrapping ]: 'clamp',
  46498. [ MirroredRepeatWrapping ]: 'mirror'
  46499. };
  46500. const gpuShaderStageLib = {
  46501. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  46502. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  46503. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  46504. };
  46505. const supports = {
  46506. instance: true,
  46507. swizzleAssign: false,
  46508. storageBuffer: true
  46509. };
  46510. const wgslFnOpLib = {
  46511. '^^': 'tsl_xor'
  46512. };
  46513. const wgslTypeLib = {
  46514. float: 'f32',
  46515. int: 'i32',
  46516. uint: 'u32',
  46517. bool: 'bool',
  46518. color: 'vec3<f32>',
  46519. vec2: 'vec2<f32>',
  46520. ivec2: 'vec2<i32>',
  46521. uvec2: 'vec2<u32>',
  46522. bvec2: 'vec2<bool>',
  46523. vec3: 'vec3<f32>',
  46524. ivec3: 'vec3<i32>',
  46525. uvec3: 'vec3<u32>',
  46526. bvec3: 'vec3<bool>',
  46527. vec4: 'vec4<f32>',
  46528. ivec4: 'vec4<i32>',
  46529. uvec4: 'vec4<u32>',
  46530. bvec4: 'vec4<bool>',
  46531. mat2: 'mat2x2<f32>',
  46532. mat3: 'mat3x3<f32>',
  46533. mat4: 'mat4x4<f32>'
  46534. };
  46535. const wgslCodeCache = {};
  46536. const wgslPolyfill = {
  46537. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  46538. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  46539. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  46540. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  46541. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  46542. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  46543. 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 ); }' ),
  46544. 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 ); }' ),
  46545. 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 ); }' ),
  46546. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  46547. 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 ); }' ),
  46548. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  46549. biquadraticTexture: new CodeNode( /* wgsl */`
  46550. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  46551. let res = vec2f( iRes );
  46552. let uvScaled = coord * res;
  46553. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  46554. // https://www.shadertoy.com/view/WtyXRy
  46555. let uv = uvWrapping - 0.5;
  46556. let iuv = floor( uv );
  46557. let f = fract( uv );
  46558. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  46559. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  46560. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  46561. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  46562. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  46563. }
  46564. ` )
  46565. };
  46566. const wgslMethods = {
  46567. dFdx: 'dpdx',
  46568. dFdy: '- dpdy',
  46569. mod_float: 'tsl_mod_float',
  46570. mod_vec2: 'tsl_mod_vec2',
  46571. mod_vec3: 'tsl_mod_vec3',
  46572. mod_vec4: 'tsl_mod_vec4',
  46573. equals_bool: 'tsl_equals_bool',
  46574. equals_bvec2: 'tsl_equals_bvec2',
  46575. equals_bvec3: 'tsl_equals_bvec3',
  46576. equals_bvec4: 'tsl_equals_bvec4',
  46577. inversesqrt: 'inverseSqrt',
  46578. bitcast: 'bitcast<f32>'
  46579. };
  46580. // WebGPU issue: does not support pow() with negative base on Windows
  46581. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  46582. 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 ); }' );
  46583. 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 ] );
  46584. 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 ] );
  46585. 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 ] );
  46586. wgslMethods.pow_float = 'tsl_pow_float';
  46587. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  46588. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  46589. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  46590. }
  46591. //
  46592. let diagnostics = '';
  46593. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  46594. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  46595. }
  46596. /**
  46597. * A node builder targeting WGSL.
  46598. *
  46599. * This module generates WGSL shader code from node materials and also
  46600. * generates the respective bindings and vertex buffer definitions. These
  46601. * data are later used by the renderer to create render and compute pipelines
  46602. * for render objects.
  46603. *
  46604. * @augments NodeBuilder
  46605. */
  46606. class WGSLNodeBuilder extends NodeBuilder {
  46607. /**
  46608. * Constructs a new WGSL node builder renderer.
  46609. *
  46610. * @param {Object3D} object - The 3D object.
  46611. * @param {Renderer} renderer - The renderer.
  46612. */
  46613. constructor( object, renderer ) {
  46614. super( object, renderer, new WGSLNodeParser() );
  46615. /**
  46616. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  46617. * another dictionary which manages UBOs per group ('render','frame','object').
  46618. *
  46619. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  46620. */
  46621. this.uniformGroups = {};
  46622. /**
  46623. * A dictionary that holds for each shader stage a Map of builtins.
  46624. *
  46625. * @type {Object<string,Map<string,Object>>}
  46626. */
  46627. this.builtins = {};
  46628. /**
  46629. * A dictionary that holds for each shader stage a Set of directives.
  46630. *
  46631. * @type {Object<string,Set<string>>}
  46632. */
  46633. this.directives = {};
  46634. /**
  46635. * A map for managing scope arrays. Only relevant for when using
  46636. * {@link WorkgroupInfoNode} in context of compute shaders.
  46637. *
  46638. * @type {Map<string,Object>}
  46639. */
  46640. this.scopedArrays = new Map();
  46641. }
  46642. /**
  46643. * Checks if the given texture requires a manual conversion to the working color space.
  46644. *
  46645. * @param {Texture} texture - The texture to check.
  46646. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  46647. */
  46648. needsToWorkingColorSpace( texture ) {
  46649. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  46650. }
  46651. /**
  46652. * Generates the WGSL snippet for sampled textures.
  46653. *
  46654. * @private
  46655. * @param {Texture} texture - The texture.
  46656. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46657. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46658. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46659. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46660. * @return {string} The WGSL snippet.
  46661. */
  46662. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46663. if ( shaderStage === 'fragment' ) {
  46664. if ( depthSnippet ) {
  46665. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  46666. } else {
  46667. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  46668. }
  46669. } else if ( this.isFilteredTexture( texture ) ) {
  46670. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  46671. } else {
  46672. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  46673. }
  46674. }
  46675. /**
  46676. * Generates the WGSL snippet when sampling video textures.
  46677. *
  46678. * @private
  46679. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  46680. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46681. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46682. * @return {string} The WGSL snippet.
  46683. */
  46684. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  46685. if ( shaderStage === 'fragment' ) {
  46686. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  46687. } else {
  46688. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  46689. }
  46690. }
  46691. /**
  46692. * Generates the WGSL snippet when sampling textures with explicit mip level.
  46693. *
  46694. * @private
  46695. * @param {Texture} texture - The texture.
  46696. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46697. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46698. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46699. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46700. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46701. * @return {string} The WGSL snippet.
  46702. */
  46703. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46704. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  46705. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  46706. } else if ( this.isFilteredTexture( texture ) ) {
  46707. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  46708. } else {
  46709. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  46710. }
  46711. }
  46712. /**
  46713. * Generates a wrap function used in context of textures.
  46714. *
  46715. * @param {Texture} texture - The texture to generate the function for.
  46716. * @return {string} The name of the generated function.
  46717. */
  46718. generateWrapFunction( texture ) {
  46719. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  46720. let nodeCode = wgslCodeCache[ functionName ];
  46721. if ( nodeCode === undefined ) {
  46722. const includes = [];
  46723. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  46724. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  46725. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  46726. const addWrapSnippet = ( wrap, axis ) => {
  46727. if ( wrap === RepeatWrapping ) {
  46728. includes.push( wgslPolyfill.repeatWrapping_float );
  46729. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  46730. } else if ( wrap === ClampToEdgeWrapping ) {
  46731. includes.push( wgslPolyfill.clampWrapping_float );
  46732. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  46733. } else if ( wrap === MirroredRepeatWrapping ) {
  46734. includes.push( wgslPolyfill.mirrorWrapping_float );
  46735. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  46736. } else {
  46737. code += `\t\tcoord.${ axis }`;
  46738. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  46739. }
  46740. };
  46741. addWrapSnippet( texture.wrapS, 'x' );
  46742. code += ',\n';
  46743. addWrapSnippet( texture.wrapT, 'y' );
  46744. if ( texture.isData3DTexture ) {
  46745. code += ',\n';
  46746. addWrapSnippet( texture.wrapR, 'z' );
  46747. }
  46748. code += '\n\t);\n\n}\n';
  46749. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  46750. }
  46751. nodeCode.build( this );
  46752. return functionName;
  46753. }
  46754. /**
  46755. * Generates the array declaration string.
  46756. *
  46757. * @param {string} type - The type.
  46758. * @param {?number} [count] - The count.
  46759. * @return {string} The generated value as a shader string.
  46760. */
  46761. generateArrayDeclaration( type, count ) {
  46762. return `array< ${ this.getType( type ) }, ${ count } >`;
  46763. }
  46764. /**
  46765. * Generates a WGSL variable that holds the texture dimension of the given texture.
  46766. * It also returns information about the number of layers (elements) of an arrayed
  46767. * texture as well as the cube face count of cube textures.
  46768. *
  46769. * @param {Texture} texture - The texture to generate the function for.
  46770. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  46771. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46772. * @return {string} The name of the dimension variable.
  46773. */
  46774. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  46775. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  46776. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  46777. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  46778. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  46779. let textureDimensionsParams;
  46780. let dimensionType;
  46781. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  46782. const isMultisampled = primarySamples > 1;
  46783. if ( texture.isData3DTexture ) {
  46784. dimensionType = 'vec3<u32>';
  46785. } else {
  46786. // Regular 2D textures, depth textures, etc.
  46787. dimensionType = 'vec2<u32>';
  46788. }
  46789. // Build parameters string based on texture type and multisampling
  46790. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  46791. textureDimensionsParams = textureProperty;
  46792. } else {
  46793. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  46794. }
  46795. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  46796. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  46797. if ( texture.isDataArrayTexture || texture.isDepthArrayTexture || texture.isData3DTexture ) {
  46798. textureData.arrayLayerCount = new VarNode(
  46799. new ExpressionNode(
  46800. `textureNumLayers(${textureProperty})`,
  46801. 'u32'
  46802. )
  46803. );
  46804. }
  46805. // For cube textures, we know it's always 6 faces
  46806. if ( texture.isTextureCube ) {
  46807. textureData.cubeFaceCount = new VarNode(
  46808. new ExpressionNode( '6u', 'u32' )
  46809. );
  46810. }
  46811. }
  46812. return textureDimensionNode.build( this );
  46813. }
  46814. /**
  46815. * Generates the WGSL snippet for a manual filtered texture.
  46816. *
  46817. * @param {Texture} texture - The texture.
  46818. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46819. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46820. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46821. * @return {string} The WGSL snippet.
  46822. */
  46823. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  46824. this._include( 'biquadraticTexture' );
  46825. const wrapFunction = this.generateWrapFunction( texture );
  46826. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  46827. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  46828. }
  46829. /**
  46830. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  46831. * Since it's a lookup, no sampling or filtering is applied.
  46832. *
  46833. * @param {Texture} texture - The texture.
  46834. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46835. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46836. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46837. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46838. * @return {string} The WGSL snippet.
  46839. */
  46840. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  46841. const wrapFunction = this.generateWrapFunction( texture );
  46842. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  46843. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  46844. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  46845. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  46846. }
  46847. /**
  46848. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  46849. *
  46850. * @param {Texture} texture - The texture.
  46851. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46852. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46853. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46854. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46855. * @return {string} The WGSL snippet.
  46856. */
  46857. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  46858. let snippet;
  46859. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  46860. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  46861. } else if ( depthSnippet ) {
  46862. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  46863. } else {
  46864. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  46865. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  46866. snippet += '.x';
  46867. }
  46868. }
  46869. return snippet;
  46870. }
  46871. /**
  46872. * Generates the WGSL snippet that writes a single texel to a texture.
  46873. *
  46874. * @param {Texture} texture - The texture.
  46875. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46876. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46877. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  46878. * @return {string} The WGSL snippet.
  46879. */
  46880. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  46881. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  46882. }
  46883. /**
  46884. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  46885. *
  46886. * @param {Texture} texture - The texture.
  46887. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  46888. */
  46889. isSampleCompare( texture ) {
  46890. return texture.isDepthTexture === true && texture.compareFunction !== null;
  46891. }
  46892. /**
  46893. * Returns `true` if the given texture is unfilterable.
  46894. *
  46895. * @param {Texture} texture - The texture.
  46896. * @return {boolean} Whether the given texture is unfilterable or not.
  46897. */
  46898. isUnfilterable( texture ) {
  46899. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  46900. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  46901. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  46902. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  46903. }
  46904. /**
  46905. * Generates the WGSL snippet for sampling/loading the given texture.
  46906. *
  46907. * @param {Texture} texture - The texture.
  46908. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46909. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46910. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46911. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46912. * @return {string} The WGSL snippet.
  46913. */
  46914. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46915. let snippet = null;
  46916. if ( texture.isVideoTexture === true ) {
  46917. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  46918. } else if ( this.isUnfilterable( texture ) ) {
  46919. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  46920. } else {
  46921. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  46922. }
  46923. return snippet;
  46924. }
  46925. /**
  46926. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  46927. *
  46928. * @param {Texture} texture - The texture.
  46929. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46930. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46931. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  46932. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46933. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46934. * @return {string} The WGSL snippet.
  46935. */
  46936. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46937. if ( shaderStage === 'fragment' ) {
  46938. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  46939. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  46940. } else {
  46941. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  46942. }
  46943. }
  46944. /**
  46945. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  46946. * against a reference value.
  46947. *
  46948. * @param {Texture} texture - The texture.
  46949. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46950. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46951. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  46952. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46953. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46954. * @return {string} The WGSL snippet.
  46955. */
  46956. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46957. if ( shaderStage === 'fragment' ) {
  46958. if ( texture.isDepthArrayTexture ) {
  46959. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  46960. }
  46961. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  46962. } else {
  46963. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  46964. }
  46965. }
  46966. /**
  46967. * Generates the WGSL snippet when sampling textures with explicit mip level.
  46968. *
  46969. * @param {Texture} texture - The texture.
  46970. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46971. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46972. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  46973. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46974. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46975. * @return {string} The WGSL snippet.
  46976. */
  46977. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46978. let snippet = null;
  46979. if ( texture.isVideoTexture === true ) {
  46980. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  46981. } else {
  46982. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  46983. }
  46984. return snippet;
  46985. }
  46986. /**
  46987. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  46988. *
  46989. * @param {Texture} texture - The texture.
  46990. * @param {string} textureProperty - The name of the texture uniform in the shader.
  46991. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  46992. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  46993. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  46994. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  46995. * @return {string} The WGSL snippet.
  46996. */
  46997. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  46998. if ( shaderStage === 'fragment' ) {
  46999. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  47000. } else {
  47001. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  47002. }
  47003. }
  47004. /**
  47005. * Returns a WGSL snippet that represents the property name of the given node.
  47006. *
  47007. * @param {Node} node - The node.
  47008. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47009. * @return {string} The property name.
  47010. */
  47011. getPropertyName( node, shaderStage = this.shaderStage ) {
  47012. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  47013. if ( shaderStage === 'vertex' ) {
  47014. return `varyings.${ node.name }`;
  47015. }
  47016. } else if ( node.isNodeUniform === true ) {
  47017. const name = node.name;
  47018. const type = node.type;
  47019. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47020. return name;
  47021. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47022. if ( this.isCustomStruct( node ) ) {
  47023. return name;
  47024. }
  47025. return name + '.value';
  47026. } else {
  47027. return node.groupNode.name + '.' + name;
  47028. }
  47029. }
  47030. return super.getPropertyName( node );
  47031. }
  47032. /**
  47033. * Returns the output struct name.
  47034. *
  47035. * @return {string} The name of the output struct.
  47036. */
  47037. getOutputStructName() {
  47038. return 'output';
  47039. }
  47040. /**
  47041. * Returns the native shader operator name for a given generic name.
  47042. *
  47043. * @param {string} op - The operator name to resolve.
  47044. * @return {?string} The resolved operator name.
  47045. */
  47046. getFunctionOperator( op ) {
  47047. const fnOp = wgslFnOpLib[ op ];
  47048. if ( fnOp !== undefined ) {
  47049. this._include( fnOp );
  47050. return fnOp;
  47051. }
  47052. return null;
  47053. }
  47054. /**
  47055. * Returns the node access for the given node and shader stage.
  47056. *
  47057. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47058. * @param {string} shaderStage - The shader stage.
  47059. * @return {string} The node access.
  47060. */
  47061. getNodeAccess( node, shaderStage ) {
  47062. if ( shaderStage !== 'compute' )
  47063. return NodeAccess.READ_ONLY;
  47064. return node.access;
  47065. }
  47066. /**
  47067. * Returns A WGSL snippet representing the storage access.
  47068. *
  47069. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47070. * @param {string} shaderStage - The shader stage.
  47071. * @return {string} The WGSL snippet representing the storage access.
  47072. */
  47073. getStorageAccess( node, shaderStage ) {
  47074. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  47075. }
  47076. /**
  47077. * This method is one of the more important ones since it's responsible
  47078. * for generating a matching binding instance for the given uniform node.
  47079. *
  47080. * These bindings are later used in the renderer to create bind groups
  47081. * and layouts.
  47082. *
  47083. * @param {UniformNode} node - The uniform node.
  47084. * @param {string} type - The node data type.
  47085. * @param {string} shaderStage - The shader stage.
  47086. * @param {?string} [name=null] - An optional uniform name.
  47087. * @return {NodeUniform} The node uniform object.
  47088. */
  47089. getUniformFromNode( node, type, shaderStage, name = null ) {
  47090. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  47091. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  47092. if ( nodeData.uniformGPU === undefined ) {
  47093. let uniformGPU;
  47094. const group = node.groupNode;
  47095. const groupName = group.name;
  47096. const bindings = this.getBindGroupArray( groupName, shaderStage );
  47097. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47098. let texture = null;
  47099. const access = this.getNodeAccess( node, shaderStage );
  47100. if ( type === 'texture' || type === 'storageTexture' ) {
  47101. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  47102. } else if ( type === 'cubeTexture' ) {
  47103. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  47104. } else if ( type === 'texture3D' ) {
  47105. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  47106. }
  47107. texture.store = node.isStorageTextureNode === true;
  47108. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47109. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  47110. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  47111. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47112. bindings.push( sampler, texture );
  47113. uniformGPU = [ sampler, texture ];
  47114. } else {
  47115. bindings.push( texture );
  47116. uniformGPU = [ texture ];
  47117. }
  47118. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47119. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  47120. const buffer = new bufferClass( node, group );
  47121. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47122. bindings.push( buffer );
  47123. uniformGPU = buffer;
  47124. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  47125. } else {
  47126. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  47127. let uniformsGroup = uniformsStage[ groupName ];
  47128. if ( uniformsGroup === undefined ) {
  47129. uniformsGroup = new NodeUniformsGroup( groupName, group );
  47130. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47131. uniformsStage[ groupName ] = uniformsGroup;
  47132. bindings.push( uniformsGroup );
  47133. }
  47134. uniformGPU = this.getNodeUniform( uniformNode, type );
  47135. uniformsGroup.addUniform( uniformGPU );
  47136. }
  47137. nodeData.uniformGPU = uniformGPU;
  47138. }
  47139. return uniformNode;
  47140. }
  47141. /**
  47142. * This method should be used whenever builtins are required in nodes.
  47143. * The internal builtins data structure will make sure builtins are
  47144. * defined in the WGSL source.
  47145. *
  47146. * @param {string} name - The builtin name.
  47147. * @param {string} property - The property name.
  47148. * @param {string} type - The node data type.
  47149. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47150. * @return {string} The property name.
  47151. */
  47152. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  47153. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  47154. if ( map.has( name ) === false ) {
  47155. map.set( name, {
  47156. name,
  47157. property,
  47158. type
  47159. } );
  47160. }
  47161. return property;
  47162. }
  47163. /**
  47164. * Returns `true` if the given builtin is defined in the given shader stage.
  47165. *
  47166. * @param {string} name - The builtin name.
  47167. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47168. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  47169. */
  47170. hasBuiltin( name, shaderStage = this.shaderStage ) {
  47171. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  47172. }
  47173. /**
  47174. * Returns the vertex index builtin.
  47175. *
  47176. * @return {string} The vertex index.
  47177. */
  47178. getVertexIndex() {
  47179. if ( this.shaderStage === 'vertex' ) {
  47180. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  47181. }
  47182. return 'vertexIndex';
  47183. }
  47184. /**
  47185. * Builds the given shader node.
  47186. *
  47187. * @param {ShaderNodeInternal} shaderNode - The shader node.
  47188. * @return {string} The WGSL function code.
  47189. */
  47190. buildFunctionCode( shaderNode ) {
  47191. const layout = shaderNode.layout;
  47192. const flowData = this.flowShaderNode( shaderNode );
  47193. const parameters = [];
  47194. for ( const input of layout.inputs ) {
  47195. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  47196. }
  47197. //
  47198. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  47199. ${ flowData.vars }
  47200. ${ flowData.code }
  47201. `;
  47202. if ( flowData.result ) {
  47203. code += `\treturn ${ flowData.result };\n`;
  47204. }
  47205. code += '\n}\n';
  47206. //
  47207. return code;
  47208. }
  47209. /**
  47210. * Returns the instance index builtin.
  47211. *
  47212. * @return {string} The instance index.
  47213. */
  47214. getInstanceIndex() {
  47215. if ( this.shaderStage === 'vertex' ) {
  47216. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  47217. }
  47218. return 'instanceIndex';
  47219. }
  47220. /**
  47221. * Returns the invocation local index builtin.
  47222. *
  47223. * @return {string} The invocation local index.
  47224. */
  47225. getInvocationLocalIndex() {
  47226. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  47227. }
  47228. /**
  47229. * Returns the subgroup size builtin.
  47230. *
  47231. * @return {string} The subgroup size.
  47232. */
  47233. getSubgroupSize() {
  47234. this.enableSubGroups();
  47235. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47236. }
  47237. /**
  47238. * Returns the invocation subgroup index builtin.
  47239. *
  47240. * @return {string} The invocation subgroup index.
  47241. */
  47242. getInvocationSubgroupIndex() {
  47243. this.enableSubGroups();
  47244. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  47245. }
  47246. /**
  47247. * Returns the subgroup index builtin.
  47248. *
  47249. * @return {string} The subgroup index.
  47250. */
  47251. getSubgroupIndex() {
  47252. this.enableSubGroups();
  47253. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  47254. }
  47255. /**
  47256. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  47257. *
  47258. * @return {null} Null.
  47259. */
  47260. getDrawIndex() {
  47261. return null;
  47262. }
  47263. /**
  47264. * Returns the front facing builtin.
  47265. *
  47266. * @return {string} The front facing builtin.
  47267. */
  47268. getFrontFacing() {
  47269. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  47270. }
  47271. /**
  47272. * Returns the frag coord builtin.
  47273. *
  47274. * @return {string} The frag coord builtin.
  47275. */
  47276. getFragCoord() {
  47277. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  47278. }
  47279. /**
  47280. * Returns the frag depth builtin.
  47281. *
  47282. * @return {string} The frag depth builtin.
  47283. */
  47284. getFragDepth() {
  47285. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  47286. }
  47287. /**
  47288. * Returns the clip distances builtin.
  47289. *
  47290. * @return {string} The clip distances builtin.
  47291. */
  47292. getClipDistance() {
  47293. return 'varyings.hw_clip_distances';
  47294. }
  47295. /**
  47296. * Whether to flip texture data along its vertical axis or not.
  47297. *
  47298. * @return {boolean} Returns always `false` in context of WGSL.
  47299. */
  47300. isFlipY() {
  47301. return false;
  47302. }
  47303. /**
  47304. * Enables the given directive for the given shader stage.
  47305. *
  47306. * @param {string} name - The directive name.
  47307. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  47308. */
  47309. enableDirective( name, shaderStage = this.shaderStage ) {
  47310. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  47311. stage.add( name );
  47312. }
  47313. /**
  47314. * Returns the directives of the given shader stage as a WGSL string.
  47315. *
  47316. * @param {string} shaderStage - The shader stage.
  47317. * @return {string} A WGSL snippet that enables the directives of the given stage.
  47318. */
  47319. getDirectives( shaderStage ) {
  47320. const snippets = [];
  47321. const directives = this.directives[ shaderStage ];
  47322. if ( directives !== undefined ) {
  47323. for ( const directive of directives ) {
  47324. snippets.push( `enable ${directive};` );
  47325. }
  47326. }
  47327. return snippets.join( '\n' );
  47328. }
  47329. /**
  47330. * Enables the 'subgroups' directive.
  47331. */
  47332. enableSubGroups() {
  47333. this.enableDirective( 'subgroups' );
  47334. }
  47335. /**
  47336. * Enables the 'subgroups-f16' directive.
  47337. */
  47338. enableSubgroupsF16() {
  47339. this.enableDirective( 'subgroups-f16' );
  47340. }
  47341. /**
  47342. * Enables the 'clip_distances' directive.
  47343. */
  47344. enableClipDistances() {
  47345. this.enableDirective( 'clip_distances' );
  47346. }
  47347. /**
  47348. * Enables the 'f16' directive.
  47349. */
  47350. enableShaderF16() {
  47351. this.enableDirective( 'f16' );
  47352. }
  47353. /**
  47354. * Enables the 'dual_source_blending' directive.
  47355. */
  47356. enableDualSourceBlending() {
  47357. this.enableDirective( 'dual_source_blending' );
  47358. }
  47359. /**
  47360. * Enables hardware clipping.
  47361. *
  47362. * @param {string} planeCount - The clipping plane count.
  47363. */
  47364. enableHardwareClipping( planeCount ) {
  47365. this.enableClipDistances();
  47366. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  47367. }
  47368. /**
  47369. * Returns the builtins of the given shader stage as a WGSL string.
  47370. *
  47371. * @param {string} shaderStage - The shader stage.
  47372. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  47373. */
  47374. getBuiltins( shaderStage ) {
  47375. const snippets = [];
  47376. const builtins = this.builtins[ shaderStage ];
  47377. if ( builtins !== undefined ) {
  47378. for ( const { name, property, type } of builtins.values() ) {
  47379. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  47380. }
  47381. }
  47382. return snippets.join( ',\n\t' );
  47383. }
  47384. /**
  47385. * This method should be used when a new scoped buffer is used in context of
  47386. * compute shaders. It adds the array to the internal data structure which is
  47387. * later used to generate the respective WGSL.
  47388. *
  47389. * @param {string} name - The array name.
  47390. * @param {string} scope - The scope.
  47391. * @param {string} bufferType - The buffer type.
  47392. * @param {string} bufferCount - The buffer count.
  47393. * @return {string} The array name.
  47394. */
  47395. getScopedArray( name, scope, bufferType, bufferCount ) {
  47396. if ( this.scopedArrays.has( name ) === false ) {
  47397. this.scopedArrays.set( name, {
  47398. name,
  47399. scope,
  47400. bufferType,
  47401. bufferCount
  47402. } );
  47403. }
  47404. return name;
  47405. }
  47406. /**
  47407. * Returns the scoped arrays of the given shader stage as a WGSL string.
  47408. *
  47409. * @param {string} shaderStage - The shader stage.
  47410. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  47411. * Returns `undefined` when used in the vertex or fragment stage.
  47412. */
  47413. getScopedArrays( shaderStage ) {
  47414. if ( shaderStage !== 'compute' ) {
  47415. return;
  47416. }
  47417. const snippets = [];
  47418. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  47419. const type = this.getType( bufferType );
  47420. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  47421. }
  47422. return snippets.join( '\n' );
  47423. }
  47424. /**
  47425. * Returns the shader attributes of the given shader stage as a WGSL string.
  47426. *
  47427. * @param {string} shaderStage - The shader stage.
  47428. * @return {string} The WGSL snippet that defines the shader attributes.
  47429. */
  47430. getAttributes( shaderStage ) {
  47431. const snippets = [];
  47432. if ( shaderStage === 'compute' ) {
  47433. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  47434. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  47435. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  47436. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  47437. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  47438. this.enableDirective( 'subgroups', shaderStage );
  47439. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47440. }
  47441. }
  47442. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  47443. const builtins = this.getBuiltins( 'attribute' );
  47444. if ( builtins ) snippets.push( builtins );
  47445. const attributes = this.getAttributesArray();
  47446. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  47447. const attribute = attributes[ index ];
  47448. const name = attribute.name;
  47449. const type = this.getType( attribute.type );
  47450. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  47451. }
  47452. }
  47453. return snippets.join( ',\n\t' );
  47454. }
  47455. /**
  47456. * Returns the members of the given struct type node as a WGSL string.
  47457. *
  47458. * @param {StructTypeNode} struct - The struct type node.
  47459. * @return {string} The WGSL snippet that defines the struct members.
  47460. */
  47461. getStructMembers( struct ) {
  47462. const snippets = [];
  47463. for ( const member of struct.members ) {
  47464. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  47465. let type = this.getType( member.type );
  47466. if ( member.atomic ) {
  47467. type = 'atomic< ' + type + ' >';
  47468. }
  47469. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  47470. }
  47471. if ( struct.output ) {
  47472. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  47473. }
  47474. return snippets.join( ',\n' );
  47475. }
  47476. /**
  47477. * Returns the structs of the given shader stage as a WGSL string.
  47478. *
  47479. * @param {string} shaderStage - The shader stage.
  47480. * @return {string} The WGSL snippet that defines the structs.
  47481. */
  47482. getStructs( shaderStage ) {
  47483. let result = '';
  47484. const structs = this.structs[ shaderStage ];
  47485. if ( structs.length > 0 ) {
  47486. const snippets = [];
  47487. for ( const struct of structs ) {
  47488. let snippet = `struct ${ struct.name } {\n`;
  47489. snippet += this.getStructMembers( struct );
  47490. snippet += '\n};';
  47491. snippets.push( snippet );
  47492. }
  47493. result = '\n' + snippets.join( '\n\n' ) + '\n';
  47494. }
  47495. return result;
  47496. }
  47497. /**
  47498. * Returns a WGSL string representing a variable.
  47499. *
  47500. * @param {string} type - The variable's type.
  47501. * @param {string} name - The variable's name.
  47502. * @param {?number} [count=null] - The array length.
  47503. * @return {string} The WGSL snippet that defines a variable.
  47504. */
  47505. getVar( type, name, count = null ) {
  47506. let snippet = `var ${ name } : `;
  47507. if ( count !== null ) {
  47508. snippet += this.generateArrayDeclaration( type, count );
  47509. } else {
  47510. snippet += this.getType( type );
  47511. }
  47512. return snippet;
  47513. }
  47514. /**
  47515. * Returns the variables of the given shader stage as a WGSL string.
  47516. *
  47517. * @param {string} shaderStage - The shader stage.
  47518. * @return {string} The WGSL snippet that defines the variables.
  47519. */
  47520. getVars( shaderStage ) {
  47521. const snippets = [];
  47522. const vars = this.vars[ shaderStage ];
  47523. if ( vars !== undefined ) {
  47524. for ( const variable of vars ) {
  47525. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  47526. }
  47527. }
  47528. return `\n${ snippets.join( '\n' ) }\n`;
  47529. }
  47530. /**
  47531. * Returns the varyings of the given shader stage as a WGSL string.
  47532. *
  47533. * @param {string} shaderStage - The shader stage.
  47534. * @return {string} The WGSL snippet that defines the varyings.
  47535. */
  47536. getVaryings( shaderStage ) {
  47537. const snippets = [];
  47538. if ( shaderStage === 'vertex' ) {
  47539. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  47540. }
  47541. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  47542. const varyings = this.varyings;
  47543. const vars = this.vars[ shaderStage ];
  47544. for ( let index = 0; index < varyings.length; index ++ ) {
  47545. const varying = varyings[ index ];
  47546. if ( varying.needsInterpolation ) {
  47547. let attributesSnippet = `@location( ${index} )`;
  47548. if ( varying.interpolationType ) {
  47549. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  47550. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  47551. // Otherwise, optimize interpolation when sensible
  47552. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  47553. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  47554. }
  47555. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  47556. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  47557. vars.push( varying );
  47558. }
  47559. }
  47560. }
  47561. const builtins = this.getBuiltins( shaderStage );
  47562. if ( builtins ) snippets.push( builtins );
  47563. const code = snippets.join( ',\n\t' );
  47564. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  47565. }
  47566. isCustomStruct( nodeUniform ) {
  47567. const attribute = nodeUniform.value;
  47568. const bufferNode = nodeUniform.node;
  47569. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  47570. const isStructArray =
  47571. ( bufferNode.value && bufferNode.value.array ) &&
  47572. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  47573. return isAttributeStructType && ! isStructArray;
  47574. }
  47575. /**
  47576. * Returns the uniforms of the given shader stage as a WGSL string.
  47577. *
  47578. * @param {string} shaderStage - The shader stage.
  47579. * @return {string} The WGSL snippet that defines the uniforms.
  47580. */
  47581. getUniforms( shaderStage ) {
  47582. const uniforms = this.uniforms[ shaderStage ];
  47583. const bindingSnippets = [];
  47584. const bufferSnippets = [];
  47585. const structSnippets = [];
  47586. const uniformGroups = {};
  47587. for ( const uniform of uniforms ) {
  47588. const groupName = uniform.groupNode.name;
  47589. const uniformIndexes = this.bindingsIndexes[ groupName ];
  47590. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  47591. const texture = uniform.node.value;
  47592. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  47593. if ( this.isSampleCompare( texture ) ) {
  47594. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  47595. } else {
  47596. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  47597. }
  47598. }
  47599. let textureType;
  47600. let multisampled = '';
  47601. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  47602. if ( primarySamples > 1 ) {
  47603. multisampled = '_multisampled';
  47604. }
  47605. if ( texture.isCubeTexture === true ) {
  47606. textureType = 'texture_cube<f32>';
  47607. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true || texture.isTextureArray === true ) {
  47608. textureType = 'texture_2d_array<f32>';
  47609. } else if ( texture.isDepthTexture === true ) {
  47610. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  47611. textureType = `texture${ multisampled }_2d<f32>`;
  47612. } else {
  47613. textureType = `texture_depth${ multisampled }_2d${ texture.isDepthArrayTexture === true ? '_array' : '' }`;
  47614. }
  47615. } else if ( texture.isVideoTexture === true ) {
  47616. textureType = 'texture_external';
  47617. } else if ( texture.isData3DTexture === true ) {
  47618. textureType = 'texture_3d<f32>';
  47619. } else if ( uniform.node.isStorageTextureNode === true ) {
  47620. const format = getFormat( texture );
  47621. const access = this.getStorageAccess( uniform.node, shaderStage );
  47622. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  47623. } else {
  47624. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  47625. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  47626. }
  47627. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  47628. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  47629. const bufferNode = uniform.node;
  47630. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  47631. const bufferCount = bufferNode.bufferCount;
  47632. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  47633. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  47634. if ( this.isCustomStruct( uniform ) ) {
  47635. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  47636. } else {
  47637. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  47638. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  47639. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  47640. }
  47641. } else {
  47642. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  47643. const groupName = uniform.groupNode.name;
  47644. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  47645. index: uniformIndexes.binding ++,
  47646. id: uniformIndexes.group,
  47647. snippets: []
  47648. } );
  47649. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  47650. }
  47651. }
  47652. for ( const name in uniformGroups ) {
  47653. const group = uniformGroups[ name ];
  47654. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  47655. }
  47656. let code = bindingSnippets.join( '\n' );
  47657. code += bufferSnippets.join( '\n' );
  47658. code += structSnippets.join( '\n' );
  47659. return code;
  47660. }
  47661. /**
  47662. * Controls the code build of the shader stages.
  47663. */
  47664. buildCode() {
  47665. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  47666. this.sortBindingGroups();
  47667. for ( const shaderStage in shadersData ) {
  47668. this.shaderStage = shaderStage;
  47669. const stageData = shadersData[ shaderStage ];
  47670. stageData.uniforms = this.getUniforms( shaderStage );
  47671. stageData.attributes = this.getAttributes( shaderStage );
  47672. stageData.varyings = this.getVaryings( shaderStage );
  47673. stageData.structs = this.getStructs( shaderStage );
  47674. stageData.vars = this.getVars( shaderStage );
  47675. stageData.codes = this.getCodes( shaderStage );
  47676. stageData.directives = this.getDirectives( shaderStage );
  47677. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  47678. //
  47679. let flow = '// code\n\n';
  47680. flow += this.flowCode[ shaderStage ];
  47681. const flowNodes = this.flowNodes[ shaderStage ];
  47682. const mainNode = flowNodes[ flowNodes.length - 1 ];
  47683. const outputNode = mainNode.outputNode;
  47684. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  47685. for ( const node of flowNodes ) {
  47686. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  47687. const slotName = node.name;
  47688. if ( slotName ) {
  47689. if ( flow.length > 0 ) flow += '\n';
  47690. flow += `\t// flow -> ${ slotName }\n`;
  47691. }
  47692. flow += `${ flowSlotData.code }\n\t`;
  47693. if ( node === mainNode && shaderStage !== 'compute' ) {
  47694. flow += '// result\n\n\t';
  47695. if ( shaderStage === 'vertex' ) {
  47696. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  47697. } else if ( shaderStage === 'fragment' ) {
  47698. if ( isOutputStruct ) {
  47699. stageData.returnType = outputNode.getNodeType( this );
  47700. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  47701. flow += `return ${ flowSlotData.result };`;
  47702. } else {
  47703. let structSnippet = '\t@location(0) color: vec4<f32>';
  47704. const builtins = this.getBuiltins( 'output' );
  47705. if ( builtins ) structSnippet += ',\n\t' + builtins;
  47706. stageData.returnType = 'OutputStruct';
  47707. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  47708. stageData.structs += '\nvar<private> output : OutputStruct;';
  47709. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  47710. }
  47711. }
  47712. }
  47713. }
  47714. stageData.flow = flow;
  47715. }
  47716. this.shaderStage = null;
  47717. if ( this.material !== null ) {
  47718. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  47719. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  47720. } else {
  47721. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  47722. }
  47723. }
  47724. /**
  47725. * Returns the native shader method name for a given generic name.
  47726. *
  47727. * @param {string} method - The method name to resolve.
  47728. * @param {?string} [output=null] - An optional output.
  47729. * @return {string} The resolved WGSL method name.
  47730. */
  47731. getMethod( method, output = null ) {
  47732. let wgslMethod;
  47733. if ( output !== null ) {
  47734. wgslMethod = this._getWGSLMethod( method + '_' + output );
  47735. }
  47736. if ( wgslMethod === undefined ) {
  47737. wgslMethod = this._getWGSLMethod( method );
  47738. }
  47739. return wgslMethod || method;
  47740. }
  47741. /**
  47742. * Returns the WGSL type of the given node data type.
  47743. *
  47744. * @param {string} type - The node data type.
  47745. * @return {string} The WGSL type.
  47746. */
  47747. getType( type ) {
  47748. return wgslTypeLib[ type ] || type;
  47749. }
  47750. /**
  47751. * Whether the requested feature is available or not.
  47752. *
  47753. * @param {string} name - The requested feature.
  47754. * @return {boolean} Whether the requested feature is supported or not.
  47755. */
  47756. isAvailable( name ) {
  47757. let result = supports[ name ];
  47758. if ( result === undefined ) {
  47759. if ( name === 'float32Filterable' ) {
  47760. result = this.renderer.hasFeature( 'float32-filterable' );
  47761. } else if ( name === 'clipDistance' ) {
  47762. result = this.renderer.hasFeature( 'clip-distances' );
  47763. }
  47764. supports[ name ] = result;
  47765. }
  47766. return result;
  47767. }
  47768. /**
  47769. * Returns the native shader method name for a given generic name.
  47770. *
  47771. * @private
  47772. * @param {string} method - The method name to resolve.
  47773. * @return {string} The resolved WGSL method name.
  47774. */
  47775. _getWGSLMethod( method ) {
  47776. if ( wgslPolyfill[ method ] !== undefined ) {
  47777. this._include( method );
  47778. }
  47779. return wgslMethods[ method ];
  47780. }
  47781. /**
  47782. * Includes the given method name into the current
  47783. * function node.
  47784. *
  47785. * @private
  47786. * @param {string} name - The method name to include.
  47787. * @return {CodeNode} The respective code node.
  47788. */
  47789. _include( name ) {
  47790. const codeNode = wgslPolyfill[ name ];
  47791. codeNode.build( this );
  47792. if ( this.currentFunctionNode !== null ) {
  47793. this.currentFunctionNode.includes.push( codeNode );
  47794. }
  47795. return codeNode;
  47796. }
  47797. /**
  47798. * Returns a WGSL vertex shader based on the given shader data.
  47799. *
  47800. * @private
  47801. * @param {Object} shaderData - The shader data.
  47802. * @return {string} The vertex shader.
  47803. */
  47804. _getWGSLVertexCode( shaderData ) {
  47805. return `${ this.getSignature() }
  47806. // directives
  47807. ${shaderData.directives}
  47808. // structs
  47809. ${shaderData.structs}
  47810. // uniforms
  47811. ${shaderData.uniforms}
  47812. // varyings
  47813. ${shaderData.varyings}
  47814. var<private> varyings : VaryingsStruct;
  47815. // codes
  47816. ${shaderData.codes}
  47817. @vertex
  47818. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  47819. // vars
  47820. ${shaderData.vars}
  47821. // flow
  47822. ${shaderData.flow}
  47823. return varyings;
  47824. }
  47825. `;
  47826. }
  47827. /**
  47828. * Returns a WGSL fragment shader based on the given shader data.
  47829. *
  47830. * @private
  47831. * @param {Object} shaderData - The shader data.
  47832. * @return {string} The vertex shader.
  47833. */
  47834. _getWGSLFragmentCode( shaderData ) {
  47835. return `${ this.getSignature() }
  47836. // global
  47837. ${ diagnostics }
  47838. // structs
  47839. ${shaderData.structs}
  47840. // uniforms
  47841. ${shaderData.uniforms}
  47842. // codes
  47843. ${shaderData.codes}
  47844. @fragment
  47845. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  47846. // vars
  47847. ${shaderData.vars}
  47848. // flow
  47849. ${shaderData.flow}
  47850. }
  47851. `;
  47852. }
  47853. /**
  47854. * Returns a WGSL compute shader based on the given shader data.
  47855. *
  47856. * @private
  47857. * @param {Object} shaderData - The shader data.
  47858. * @param {string} workgroupSize - The workgroup size.
  47859. * @return {string} The vertex shader.
  47860. */
  47861. _getWGSLComputeCode( shaderData, workgroupSize ) {
  47862. return `${ this.getSignature() }
  47863. // directives
  47864. ${shaderData.directives}
  47865. // system
  47866. var<private> instanceIndex : u32;
  47867. // locals
  47868. ${shaderData.scopedArrays}
  47869. // structs
  47870. ${shaderData.structs}
  47871. // uniforms
  47872. ${shaderData.uniforms}
  47873. // codes
  47874. ${shaderData.codes}
  47875. @compute @workgroup_size( ${workgroupSize} )
  47876. fn main( ${shaderData.attributes} ) {
  47877. // system
  47878. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  47879. // vars
  47880. ${shaderData.vars}
  47881. // flow
  47882. ${shaderData.flow}
  47883. }
  47884. `;
  47885. }
  47886. /**
  47887. * Returns a WGSL struct based on the given name and variables.
  47888. *
  47889. * @private
  47890. * @param {string} name - The struct name.
  47891. * @param {string} vars - The struct variables.
  47892. * @return {string} The WGSL snippet representing a struct.
  47893. */
  47894. _getWGSLStruct( name, vars ) {
  47895. return `
  47896. struct ${name} {
  47897. ${vars}
  47898. };`;
  47899. }
  47900. /**
  47901. * Returns a WGSL struct binding.
  47902. *
  47903. * @private
  47904. * @param {string} name - The struct name.
  47905. * @param {string} vars - The struct variables.
  47906. * @param {string} access - The access.
  47907. * @param {number} [binding=0] - The binding index.
  47908. * @param {number} [group=0] - The group index.
  47909. * @return {string} The WGSL snippet representing a struct binding.
  47910. */
  47911. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  47912. const structName = name + 'Struct';
  47913. const structSnippet = this._getWGSLStruct( structName, vars );
  47914. return `${structSnippet}
  47915. @binding( ${ binding } ) @group( ${ group } )
  47916. var<${access}> ${ name } : ${ structName };`;
  47917. }
  47918. }
  47919. /**
  47920. * A WebGPU backend utility module with common helpers.
  47921. *
  47922. * @private
  47923. */
  47924. class WebGPUUtils {
  47925. /**
  47926. * Constructs a new utility object.
  47927. *
  47928. * @param {WebGPUBackend} backend - The WebGPU backend.
  47929. */
  47930. constructor( backend ) {
  47931. /**
  47932. * A reference to the WebGPU backend.
  47933. *
  47934. * @type {WebGPUBackend}
  47935. */
  47936. this.backend = backend;
  47937. }
  47938. /**
  47939. * Returns the depth/stencil GPU format for the given render context.
  47940. *
  47941. * @param {RenderContext} renderContext - The render context.
  47942. * @return {string} The depth/stencil GPU texture format.
  47943. */
  47944. getCurrentDepthStencilFormat( renderContext ) {
  47945. let format;
  47946. if ( renderContext.depthTexture !== null ) {
  47947. format = this.getTextureFormatGPU( renderContext.depthTexture );
  47948. } else if ( renderContext.depth && renderContext.stencil ) {
  47949. format = GPUTextureFormat.Depth24PlusStencil8;
  47950. } else if ( renderContext.depth ) {
  47951. format = GPUTextureFormat.Depth24Plus;
  47952. }
  47953. return format;
  47954. }
  47955. /**
  47956. * Returns the GPU format for the given texture.
  47957. *
  47958. * @param {Texture} texture - The texture.
  47959. * @return {string} The GPU texture format.
  47960. */
  47961. getTextureFormatGPU( texture ) {
  47962. return this.backend.get( texture ).format;
  47963. }
  47964. /**
  47965. * Returns an object that defines the multi-sampling state of the given texture.
  47966. *
  47967. * @param {Texture} texture - The texture.
  47968. * @return {Object} The multi-sampling state.
  47969. */
  47970. getTextureSampleData( texture ) {
  47971. let samples;
  47972. if ( texture.isFramebufferTexture ) {
  47973. samples = 1;
  47974. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  47975. const renderer = this.backend.renderer;
  47976. const renderTarget = renderer.getRenderTarget();
  47977. samples = renderTarget ? renderTarget.samples : renderer.samples;
  47978. } else if ( texture.renderTarget ) {
  47979. samples = texture.renderTarget.samples;
  47980. }
  47981. samples = samples || 1;
  47982. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  47983. const primarySamples = isMSAA ? 1 : samples;
  47984. return { samples, primarySamples, isMSAA };
  47985. }
  47986. /**
  47987. * Returns the default color attachment's GPU format of the current render context.
  47988. *
  47989. * @param {RenderContext} renderContext - The render context.
  47990. * @return {string} The GPU texture format of the default color attachment.
  47991. */
  47992. getCurrentColorFormat( renderContext ) {
  47993. let format;
  47994. if ( renderContext.textures !== null ) {
  47995. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  47996. } else {
  47997. format = this.getPreferredCanvasFormat(); // default context format
  47998. }
  47999. return format;
  48000. }
  48001. /**
  48002. * Returns the output color space of the current render context.
  48003. *
  48004. * @param {RenderContext} renderContext - The render context.
  48005. * @return {string} The output color space.
  48006. */
  48007. getCurrentColorSpace( renderContext ) {
  48008. if ( renderContext.textures !== null ) {
  48009. return renderContext.textures[ 0 ].colorSpace;
  48010. }
  48011. return this.backend.renderer.outputColorSpace;
  48012. }
  48013. /**
  48014. * Returns GPU primitive topology for the given object and material.
  48015. *
  48016. * @param {Object3D} object - The 3D object.
  48017. * @param {Material} material - The material.
  48018. * @return {string} The GPU primitive topology.
  48019. */
  48020. getPrimitiveTopology( object, material ) {
  48021. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  48022. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  48023. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  48024. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  48025. }
  48026. /**
  48027. * Returns a modified sample count from the given sample count value.
  48028. *
  48029. * That is required since WebGPU does not support arbitrary sample counts.
  48030. *
  48031. * @param {number} sampleCount - The input sample count.
  48032. * @return {number} The (potentially updated) output sample count.
  48033. */
  48034. getSampleCount( sampleCount ) {
  48035. let count = 1;
  48036. if ( sampleCount > 1 ) {
  48037. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  48038. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  48039. if ( count === 2 ) {
  48040. count = 4;
  48041. }
  48042. }
  48043. return count;
  48044. }
  48045. /**
  48046. * Returns the sample count of the given render context.
  48047. *
  48048. * @param {RenderContext} renderContext - The render context.
  48049. * @return {number} The sample count.
  48050. */
  48051. getSampleCountRenderContext( renderContext ) {
  48052. if ( renderContext.textures !== null ) {
  48053. return this.getSampleCount( renderContext.sampleCount );
  48054. }
  48055. return this.getSampleCount( this.backend.renderer.samples );
  48056. }
  48057. /**
  48058. * Returns the preferred canvas format.
  48059. *
  48060. * There is a separate method for this so it's possible to
  48061. * honor edge cases for specific devices.
  48062. *
  48063. * @return {string} The GPU texture format of the canvas.
  48064. */
  48065. getPreferredCanvasFormat() {
  48066. const outputType = this.backend.parameters.outputType;
  48067. if ( outputType === undefined ) {
  48068. return navigator.gpu.getPreferredCanvasFormat();
  48069. } else if ( outputType === UnsignedByteType ) {
  48070. return GPUTextureFormat.BGRA8Unorm;
  48071. } else if ( outputType === HalfFloatType ) {
  48072. return GPUTextureFormat.RGBA16Float;
  48073. } else {
  48074. throw new Error( 'Unsupported outputType' );
  48075. }
  48076. }
  48077. }
  48078. const typedArraysToVertexFormatPrefix = new Map( [
  48079. [ Int8Array, [ 'sint8', 'snorm8' ]],
  48080. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  48081. [ Int16Array, [ 'sint16', 'snorm16' ]],
  48082. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  48083. [ Int32Array, [ 'sint32', 'snorm32' ]],
  48084. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  48085. [ Float32Array, [ 'float32', ]],
  48086. ] );
  48087. const typedAttributeToVertexFormatPrefix = new Map( [
  48088. [ Float16BufferAttribute, [ 'float16', ]],
  48089. ] );
  48090. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  48091. [ Int32Array, 'sint32' ],
  48092. [ Int16Array, 'sint32' ], // patch for INT16
  48093. [ Uint32Array, 'uint32' ],
  48094. [ Uint16Array, 'uint32' ], // patch for UINT16
  48095. [ Float32Array, 'float32' ]
  48096. ] );
  48097. /**
  48098. * A WebGPU backend utility module for managing shader attributes.
  48099. *
  48100. * @private
  48101. */
  48102. class WebGPUAttributeUtils {
  48103. /**
  48104. * Constructs a new utility object.
  48105. *
  48106. * @param {WebGPUBackend} backend - The WebGPU backend.
  48107. */
  48108. constructor( backend ) {
  48109. /**
  48110. * A reference to the WebGPU backend.
  48111. *
  48112. * @type {WebGPUBackend}
  48113. */
  48114. this.backend = backend;
  48115. }
  48116. /**
  48117. * Creates the GPU buffer for the given buffer attribute.
  48118. *
  48119. * @param {BufferAttribute} attribute - The buffer attribute.
  48120. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  48121. */
  48122. createAttribute( attribute, usage ) {
  48123. const bufferAttribute = this._getBufferAttribute( attribute );
  48124. const backend = this.backend;
  48125. const bufferData = backend.get( bufferAttribute );
  48126. let buffer = bufferData.buffer;
  48127. if ( buffer === undefined ) {
  48128. const device = backend.device;
  48129. let array = bufferAttribute.array;
  48130. // patch for INT16 and UINT16
  48131. if ( attribute.normalized === false ) {
  48132. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  48133. array = new Int32Array( array );
  48134. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  48135. array = new Uint32Array( array );
  48136. if ( usage & GPUBufferUsage.INDEX ) {
  48137. for ( let i = 0; i < array.length; i ++ ) {
  48138. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  48139. }
  48140. }
  48141. }
  48142. }
  48143. bufferAttribute.array = array;
  48144. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  48145. array = new array.constructor( bufferAttribute.count * 4 );
  48146. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48147. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48148. }
  48149. // Update BufferAttribute
  48150. bufferAttribute.itemSize = 4;
  48151. bufferAttribute.array = array;
  48152. bufferData._force3to4BytesAlignment = true;
  48153. }
  48154. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  48155. buffer = device.createBuffer( {
  48156. label: bufferAttribute.name,
  48157. size: size,
  48158. usage: usage,
  48159. mappedAtCreation: true
  48160. } );
  48161. new array.constructor( buffer.getMappedRange() ).set( array );
  48162. buffer.unmap();
  48163. bufferData.buffer = buffer;
  48164. }
  48165. }
  48166. /**
  48167. * Updates the GPU buffer of the given buffer attribute.
  48168. *
  48169. * @param {BufferAttribute} attribute - The buffer attribute.
  48170. */
  48171. updateAttribute( attribute ) {
  48172. const bufferAttribute = this._getBufferAttribute( attribute );
  48173. const backend = this.backend;
  48174. const device = backend.device;
  48175. const bufferData = backend.get( bufferAttribute );
  48176. const buffer = backend.get( bufferAttribute ).buffer;
  48177. let array = bufferAttribute.array;
  48178. // if storage buffer ensure 4 byte alignment
  48179. if ( bufferData._force3to4BytesAlignment === true ) {
  48180. array = new array.constructor( bufferAttribute.count * 4 );
  48181. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48182. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48183. }
  48184. bufferAttribute.array = array;
  48185. }
  48186. const isTypedArray = this._isTypedArray( array );
  48187. const updateRanges = bufferAttribute.updateRanges;
  48188. if ( updateRanges.length === 0 ) {
  48189. // Not using update ranges
  48190. device.queue.writeBuffer(
  48191. buffer,
  48192. 0,
  48193. array,
  48194. 0
  48195. );
  48196. } else {
  48197. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  48198. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  48199. const range = updateRanges[ i ];
  48200. let dataOffset, size;
  48201. if ( bufferData._force3to4BytesAlignment === true ) {
  48202. const vertexStart = Math.floor( range.start / 3 );
  48203. const vertexCount = Math.ceil( range.count / 3 );
  48204. dataOffset = vertexStart * 4 * byteOffsetFactor;
  48205. size = vertexCount * 4 * byteOffsetFactor;
  48206. } else {
  48207. dataOffset = range.start * byteOffsetFactor;
  48208. size = range.count * byteOffsetFactor;
  48209. }
  48210. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  48211. device.queue.writeBuffer(
  48212. buffer,
  48213. bufferOffset,
  48214. array,
  48215. dataOffset,
  48216. size
  48217. );
  48218. }
  48219. bufferAttribute.clearUpdateRanges();
  48220. }
  48221. }
  48222. /**
  48223. * This method creates the vertex buffer layout data which are
  48224. * require when creating a render pipeline for the given render object.
  48225. *
  48226. * @param {RenderObject} renderObject - The render object.
  48227. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  48228. */
  48229. createShaderVertexBuffers( renderObject ) {
  48230. const attributes = renderObject.getAttributes();
  48231. const vertexBuffers = new Map();
  48232. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  48233. const geometryAttribute = attributes[ slot ];
  48234. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  48235. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  48236. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  48237. if ( vertexBufferLayout === undefined ) {
  48238. let arrayStride, stepMode;
  48239. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  48240. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  48241. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48242. } else {
  48243. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  48244. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48245. }
  48246. // patch for INT16 and UINT16
  48247. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  48248. arrayStride = 4;
  48249. }
  48250. vertexBufferLayout = {
  48251. arrayStride,
  48252. attributes: [],
  48253. stepMode
  48254. };
  48255. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  48256. }
  48257. const format = this._getVertexFormat( geometryAttribute );
  48258. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  48259. vertexBufferLayout.attributes.push( {
  48260. shaderLocation: slot,
  48261. offset,
  48262. format
  48263. } );
  48264. }
  48265. return Array.from( vertexBuffers.values() );
  48266. }
  48267. /**
  48268. * Destroys the GPU buffer of the given buffer attribute.
  48269. *
  48270. * @param {BufferAttribute} attribute - The buffer attribute.
  48271. */
  48272. destroyAttribute( attribute ) {
  48273. const backend = this.backend;
  48274. const data = backend.get( this._getBufferAttribute( attribute ) );
  48275. data.buffer.destroy();
  48276. backend.delete( attribute );
  48277. }
  48278. /**
  48279. * This method performs a readback operation by moving buffer data from
  48280. * a storage buffer attribute from the GPU to the CPU.
  48281. *
  48282. * @async
  48283. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48284. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48285. */
  48286. async getArrayBufferAsync( attribute ) {
  48287. const backend = this.backend;
  48288. const device = backend.device;
  48289. const data = backend.get( this._getBufferAttribute( attribute ) );
  48290. const bufferGPU = data.buffer;
  48291. const size = bufferGPU.size;
  48292. const readBufferGPU = device.createBuffer( {
  48293. label: `${ attribute.name }_readback`,
  48294. size,
  48295. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48296. } );
  48297. const cmdEncoder = device.createCommandEncoder( {
  48298. label: `readback_encoder_${ attribute.name }`
  48299. } );
  48300. cmdEncoder.copyBufferToBuffer(
  48301. bufferGPU,
  48302. 0,
  48303. readBufferGPU,
  48304. 0,
  48305. size
  48306. );
  48307. const gpuCommands = cmdEncoder.finish();
  48308. device.queue.submit( [ gpuCommands ] );
  48309. await readBufferGPU.mapAsync( GPUMapMode.READ );
  48310. const arrayBuffer = readBufferGPU.getMappedRange();
  48311. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  48312. readBufferGPU.unmap();
  48313. return dstBuffer.buffer;
  48314. }
  48315. /**
  48316. * Returns the vertex format of the given buffer attribute.
  48317. *
  48318. * @private
  48319. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  48320. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  48321. */
  48322. _getVertexFormat( geometryAttribute ) {
  48323. const { itemSize, normalized } = geometryAttribute;
  48324. const ArrayType = geometryAttribute.array.constructor;
  48325. const AttributeType = geometryAttribute.constructor;
  48326. let format;
  48327. if ( itemSize === 1 ) {
  48328. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  48329. } else {
  48330. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  48331. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  48332. if ( prefix ) {
  48333. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  48334. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  48335. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  48336. if ( paddedItemSize % 1 ) {
  48337. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  48338. }
  48339. format = `${prefix}x${paddedItemSize}`;
  48340. }
  48341. }
  48342. if ( ! format ) {
  48343. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  48344. }
  48345. return format;
  48346. }
  48347. /**
  48348. * Returns `true` if the given array is a typed array.
  48349. *
  48350. * @private
  48351. * @param {any} array - The array.
  48352. * @return {boolean} Whether the given array is a typed array or not.
  48353. */
  48354. _isTypedArray( array ) {
  48355. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  48356. }
  48357. /**
  48358. * Utility method for handling interleaved buffer attributes correctly.
  48359. * To process them, their `InterleavedBuffer` is returned.
  48360. *
  48361. * @private
  48362. * @param {BufferAttribute} attribute - The attribute.
  48363. * @return {BufferAttribute|InterleavedBuffer}
  48364. */
  48365. _getBufferAttribute( attribute ) {
  48366. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  48367. return attribute;
  48368. }
  48369. }
  48370. /**
  48371. * A WebGPU backend utility module for managing bindings.
  48372. *
  48373. * When reading the documentation it's helpful to keep in mind that
  48374. * all class definitions starting with 'GPU*' are modules from the
  48375. * WebGPU API. So for example `BindGroup` is a class from the engine
  48376. * whereas `GPUBindGroup` is a class from WebGPU.
  48377. *
  48378. * @private
  48379. */
  48380. class WebGPUBindingUtils {
  48381. /**
  48382. * Constructs a new utility object.
  48383. *
  48384. * @param {WebGPUBackend} backend - The WebGPU backend.
  48385. */
  48386. constructor( backend ) {
  48387. /**
  48388. * A reference to the WebGPU backend.
  48389. *
  48390. * @type {WebGPUBackend}
  48391. */
  48392. this.backend = backend;
  48393. /**
  48394. * A cache for managing bind group layouts.
  48395. *
  48396. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  48397. */
  48398. this.bindGroupLayoutCache = new WeakMap();
  48399. }
  48400. /**
  48401. * Creates a GPU bind group layout for the given bind group.
  48402. *
  48403. * @param {BindGroup} bindGroup - The bind group.
  48404. * @return {GPUBindGroupLayout} The GPU bind group layout.
  48405. */
  48406. createBindingsLayout( bindGroup ) {
  48407. const backend = this.backend;
  48408. const device = backend.device;
  48409. const entries = [];
  48410. let index = 0;
  48411. for ( const binding of bindGroup.bindings ) {
  48412. const bindingGPU = {
  48413. binding: index ++,
  48414. visibility: binding.visibility
  48415. };
  48416. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  48417. const buffer = {}; // GPUBufferBindingLayout
  48418. if ( binding.isStorageBuffer ) {
  48419. if ( binding.visibility & 4 ) {
  48420. // compute
  48421. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  48422. buffer.type = GPUBufferBindingType.Storage;
  48423. } else {
  48424. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  48425. }
  48426. } else {
  48427. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  48428. }
  48429. }
  48430. bindingGPU.buffer = buffer;
  48431. } else if ( binding.isSampler ) {
  48432. const sampler = {}; // GPUSamplerBindingLayout
  48433. if ( binding.texture.isDepthTexture ) {
  48434. if ( binding.texture.compareFunction !== null ) {
  48435. sampler.type = GPUSamplerBindingType.Comparison;
  48436. } else if ( backend.compatibilityMode ) {
  48437. sampler.type = GPUSamplerBindingType.NonFiltering;
  48438. }
  48439. }
  48440. bindingGPU.sampler = sampler;
  48441. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  48442. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  48443. } else if ( binding.isSampledTexture && binding.store ) {
  48444. const storageTexture = {}; // GPUStorageTextureBindingLayout
  48445. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  48446. const access = binding.access;
  48447. if ( access === NodeAccess.READ_WRITE ) {
  48448. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  48449. } else if ( access === NodeAccess.WRITE_ONLY ) {
  48450. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  48451. } else {
  48452. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  48453. }
  48454. bindingGPU.storageTexture = storageTexture;
  48455. } else if ( binding.isSampledTexture ) {
  48456. const texture = {}; // GPUTextureBindingLayout
  48457. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  48458. if ( primarySamples > 1 ) {
  48459. texture.multisampled = true;
  48460. if ( ! binding.texture.isDepthTexture ) {
  48461. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48462. }
  48463. }
  48464. if ( binding.texture.isDepthTexture ) {
  48465. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  48466. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48467. } else {
  48468. texture.sampleType = GPUTextureSampleType.Depth;
  48469. }
  48470. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  48471. const type = binding.texture.type;
  48472. if ( type === IntType ) {
  48473. texture.sampleType = GPUTextureSampleType.SInt;
  48474. } else if ( type === UnsignedIntType ) {
  48475. texture.sampleType = GPUTextureSampleType.UInt;
  48476. } else if ( type === FloatType ) {
  48477. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  48478. texture.sampleType = GPUTextureSampleType.Float;
  48479. } else {
  48480. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  48481. }
  48482. }
  48483. }
  48484. if ( binding.isSampledCubeTexture ) {
  48485. texture.viewDimension = GPUTextureViewDimension.Cube;
  48486. } else if ( binding.texture.isDataArrayTexture || binding.texture.isDepthArrayTexture || binding.texture.isCompressedArrayTexture ) {
  48487. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  48488. } else if ( binding.isSampledTexture3D ) {
  48489. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  48490. }
  48491. bindingGPU.texture = texture;
  48492. } else {
  48493. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  48494. }
  48495. entries.push( bindingGPU );
  48496. }
  48497. return device.createBindGroupLayout( { entries } );
  48498. }
  48499. /**
  48500. * Creates bindings from the given bind group definition.
  48501. *
  48502. * @param {BindGroup} bindGroup - The bind group.
  48503. * @param {Array<BindGroup>} bindings - Array of bind groups.
  48504. * @param {number} cacheIndex - The cache index.
  48505. * @param {number} version - The version.
  48506. */
  48507. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  48508. const { backend, bindGroupLayoutCache } = this;
  48509. const bindingsData = backend.get( bindGroup );
  48510. // setup (static) binding layout and (dynamic) binding group
  48511. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  48512. if ( bindLayoutGPU === undefined ) {
  48513. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  48514. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  48515. }
  48516. let bindGroupGPU;
  48517. if ( cacheIndex > 0 ) {
  48518. if ( bindingsData.groups === undefined ) {
  48519. bindingsData.groups = [];
  48520. bindingsData.versions = [];
  48521. }
  48522. if ( bindingsData.versions[ cacheIndex ] === version ) {
  48523. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  48524. }
  48525. }
  48526. if ( bindGroupGPU === undefined ) {
  48527. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  48528. if ( cacheIndex > 0 ) {
  48529. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  48530. bindingsData.versions[ cacheIndex ] = version;
  48531. }
  48532. }
  48533. bindingsData.group = bindGroupGPU;
  48534. bindingsData.layout = bindLayoutGPU;
  48535. }
  48536. /**
  48537. * Updates a buffer binding.
  48538. *
  48539. * @param {Buffer} binding - The buffer binding to update.
  48540. */
  48541. updateBinding( binding ) {
  48542. const backend = this.backend;
  48543. const device = backend.device;
  48544. const buffer = binding.buffer;
  48545. const bufferGPU = backend.get( binding ).buffer;
  48546. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  48547. }
  48548. /**
  48549. * Creates a GPU bind group for the camera index.
  48550. *
  48551. * @param {Uint32Array} data - The index data.
  48552. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  48553. * @return {GPUBindGroup} The GPU bind group.
  48554. */
  48555. createBindGroupIndex( data, layout ) {
  48556. const backend = this.backend;
  48557. const device = backend.device;
  48558. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  48559. const index = data[ 0 ];
  48560. const buffer = device.createBuffer( {
  48561. label: 'bindingCameraIndex_' + index,
  48562. size: 16, // uint(4) * 4
  48563. usage: usage
  48564. } );
  48565. device.queue.writeBuffer( buffer, 0, data, 0 );
  48566. const entries = [ { binding: 0, resource: { buffer } } ];
  48567. return device.createBindGroup( {
  48568. label: 'bindGroupCameraIndex_' + index,
  48569. layout,
  48570. entries
  48571. } );
  48572. }
  48573. /**
  48574. * Creates a GPU bind group for the given bind group and GPU layout.
  48575. *
  48576. * @param {BindGroup} bindGroup - The bind group.
  48577. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  48578. * @return {GPUBindGroup} The GPU bind group.
  48579. */
  48580. createBindGroup( bindGroup, layoutGPU ) {
  48581. const backend = this.backend;
  48582. const device = backend.device;
  48583. let bindingPoint = 0;
  48584. const entriesGPU = [];
  48585. for ( const binding of bindGroup.bindings ) {
  48586. if ( binding.isUniformBuffer ) {
  48587. const bindingData = backend.get( binding );
  48588. if ( bindingData.buffer === undefined ) {
  48589. const byteLength = binding.byteLength;
  48590. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  48591. const bufferGPU = device.createBuffer( {
  48592. label: 'bindingBuffer_' + binding.name,
  48593. size: byteLength,
  48594. usage: usage
  48595. } );
  48596. bindingData.buffer = bufferGPU;
  48597. }
  48598. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  48599. } else if ( binding.isStorageBuffer ) {
  48600. const bindingData = backend.get( binding );
  48601. if ( bindingData.buffer === undefined ) {
  48602. const attribute = binding.attribute;
  48603. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  48604. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  48605. bindingData.buffer = backend.get( attribute ).buffer;
  48606. }
  48607. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  48608. } else if ( binding.isSampler ) {
  48609. const textureGPU = backend.get( binding.texture );
  48610. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  48611. } else if ( binding.isSampledTexture ) {
  48612. const textureData = backend.get( binding.texture );
  48613. let resourceGPU;
  48614. if ( textureData.externalTexture !== undefined ) {
  48615. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  48616. } else {
  48617. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  48618. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  48619. resourceGPU = textureData[ propertyName ];
  48620. if ( resourceGPU === undefined ) {
  48621. const aspectGPU = GPUTextureAspect.All;
  48622. let dimensionViewGPU;
  48623. if ( binding.isSampledCubeTexture ) {
  48624. dimensionViewGPU = GPUTextureViewDimension.Cube;
  48625. } else if ( binding.isSampledTexture3D ) {
  48626. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  48627. } else if ( binding.texture.isDataArrayTexture || binding.texture.isDepthArrayTexture || binding.texture.isCompressedArrayTexture ) {
  48628. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  48629. } else {
  48630. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  48631. }
  48632. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  48633. }
  48634. }
  48635. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  48636. }
  48637. bindingPoint ++;
  48638. }
  48639. return device.createBindGroup( {
  48640. label: 'bindGroup_' + bindGroup.name,
  48641. layout: layoutGPU,
  48642. entries: entriesGPU
  48643. } );
  48644. }
  48645. }
  48646. /**
  48647. * A WebGPU backend utility module for managing pipelines.
  48648. *
  48649. * @private
  48650. */
  48651. class WebGPUPipelineUtils {
  48652. /**
  48653. * Constructs a new utility object.
  48654. *
  48655. * @param {WebGPUBackend} backend - The WebGPU backend.
  48656. */
  48657. constructor( backend ) {
  48658. /**
  48659. * A reference to the WebGPU backend.
  48660. *
  48661. * @type {WebGPUBackend}
  48662. */
  48663. this.backend = backend;
  48664. }
  48665. /**
  48666. * Returns the sample count derived from the given render context.
  48667. *
  48668. * @private
  48669. * @param {RenderContext} renderContext - The render context.
  48670. * @return {number} The sample count.
  48671. */
  48672. _getSampleCount( renderContext ) {
  48673. return this.backend.utils.getSampleCountRenderContext( renderContext );
  48674. }
  48675. /**
  48676. * Creates a render pipeline for the given render object.
  48677. *
  48678. * @param {RenderObject} renderObject - The render object.
  48679. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  48680. */
  48681. createRenderPipeline( renderObject, promises ) {
  48682. const { object, material, geometry, pipeline } = renderObject;
  48683. const { vertexProgram, fragmentProgram } = pipeline;
  48684. const backend = this.backend;
  48685. const device = backend.device;
  48686. const utils = backend.utils;
  48687. const pipelineData = backend.get( pipeline );
  48688. // bind group layouts
  48689. const bindGroupLayouts = [];
  48690. for ( const bindGroup of renderObject.getBindings() ) {
  48691. const bindingsData = backend.get( bindGroup );
  48692. bindGroupLayouts.push( bindingsData.layout );
  48693. }
  48694. // vertex buffers
  48695. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  48696. // blending
  48697. let blending;
  48698. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  48699. blending = this._getBlending( material );
  48700. }
  48701. // stencil
  48702. let stencilFront = {};
  48703. if ( material.stencilWrite === true ) {
  48704. stencilFront = {
  48705. compare: this._getStencilCompare( material ),
  48706. failOp: this._getStencilOperation( material.stencilFail ),
  48707. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  48708. passOp: this._getStencilOperation( material.stencilZPass )
  48709. };
  48710. }
  48711. const colorWriteMask = this._getColorWriteMask( material );
  48712. const targets = [];
  48713. if ( renderObject.context.textures !== null ) {
  48714. const textures = renderObject.context.textures;
  48715. for ( let i = 0; i < textures.length; i ++ ) {
  48716. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  48717. targets.push( {
  48718. format: colorFormat,
  48719. blend: blending,
  48720. writeMask: colorWriteMask
  48721. } );
  48722. }
  48723. } else {
  48724. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  48725. targets.push( {
  48726. format: colorFormat,
  48727. blend: blending,
  48728. writeMask: colorWriteMask
  48729. } );
  48730. }
  48731. const vertexModule = backend.get( vertexProgram ).module;
  48732. const fragmentModule = backend.get( fragmentProgram ).module;
  48733. const primitiveState = this._getPrimitiveState( object, geometry, material );
  48734. const depthCompare = this._getDepthCompare( material );
  48735. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  48736. const sampleCount = this._getSampleCount( renderObject.context );
  48737. const pipelineDescriptor = {
  48738. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  48739. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  48740. fragment: Object.assign( {}, fragmentModule, { targets } ),
  48741. primitive: primitiveState,
  48742. multisample: {
  48743. count: sampleCount,
  48744. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  48745. },
  48746. layout: device.createPipelineLayout( {
  48747. bindGroupLayouts
  48748. } )
  48749. };
  48750. const depthStencil = {};
  48751. const renderDepth = renderObject.context.depth;
  48752. const renderStencil = renderObject.context.stencil;
  48753. if ( renderDepth === true || renderStencil === true ) {
  48754. if ( renderDepth === true ) {
  48755. depthStencil.format = depthStencilFormat;
  48756. depthStencil.depthWriteEnabled = material.depthWrite;
  48757. depthStencil.depthCompare = depthCompare;
  48758. }
  48759. if ( renderStencil === true ) {
  48760. depthStencil.stencilFront = stencilFront;
  48761. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  48762. depthStencil.stencilReadMask = material.stencilFuncMask;
  48763. depthStencil.stencilWriteMask = material.stencilWriteMask;
  48764. }
  48765. if ( material.polygonOffset === true ) {
  48766. depthStencil.depthBias = material.polygonOffsetUnits;
  48767. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  48768. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  48769. }
  48770. pipelineDescriptor.depthStencil = depthStencil;
  48771. }
  48772. if ( promises === null ) {
  48773. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  48774. } else {
  48775. const p = new Promise( ( resolve /*, reject*/ ) => {
  48776. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  48777. pipelineData.pipeline = pipeline;
  48778. resolve();
  48779. } );
  48780. } );
  48781. promises.push( p );
  48782. }
  48783. }
  48784. /**
  48785. * Creates GPU render bundle encoder for the given render context.
  48786. *
  48787. * @param {RenderContext} renderContext - The render context.
  48788. * @param {?string} [label='renderBundleEncoder'] - The label.
  48789. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  48790. */
  48791. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  48792. const backend = this.backend;
  48793. const { utils, device } = backend;
  48794. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  48795. const colorFormat = utils.getCurrentColorFormat( renderContext );
  48796. const sampleCount = this._getSampleCount( renderContext );
  48797. const descriptor = {
  48798. label: label,
  48799. colorFormats: [ colorFormat ],
  48800. depthStencilFormat,
  48801. sampleCount
  48802. };
  48803. return device.createRenderBundleEncoder( descriptor );
  48804. }
  48805. /**
  48806. * Creates a compute pipeline for the given compute node.
  48807. *
  48808. * @param {ComputePipeline} pipeline - The compute pipeline.
  48809. * @param {Array<BindGroup>} bindings - The bindings.
  48810. */
  48811. createComputePipeline( pipeline, bindings ) {
  48812. const backend = this.backend;
  48813. const device = backend.device;
  48814. const computeProgram = backend.get( pipeline.computeProgram ).module;
  48815. const pipelineGPU = backend.get( pipeline );
  48816. // bind group layouts
  48817. const bindGroupLayouts = [];
  48818. for ( const bindingsGroup of bindings ) {
  48819. const bindingsData = backend.get( bindingsGroup );
  48820. bindGroupLayouts.push( bindingsData.layout );
  48821. }
  48822. pipelineGPU.pipeline = device.createComputePipeline( {
  48823. compute: computeProgram,
  48824. layout: device.createPipelineLayout( {
  48825. bindGroupLayouts
  48826. } )
  48827. } );
  48828. }
  48829. /**
  48830. * Returns the blending state as a descriptor object required
  48831. * for the pipeline creation.
  48832. *
  48833. * @private
  48834. * @param {Material} material - The material.
  48835. * @return {Object} The blending state.
  48836. */
  48837. _getBlending( material ) {
  48838. let color, alpha;
  48839. const blending = material.blending;
  48840. const blendSrc = material.blendSrc;
  48841. const blendDst = material.blendDst;
  48842. const blendEquation = material.blendEquation;
  48843. if ( blending === CustomBlending ) {
  48844. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  48845. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  48846. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  48847. color = {
  48848. srcFactor: this._getBlendFactor( blendSrc ),
  48849. dstFactor: this._getBlendFactor( blendDst ),
  48850. operation: this._getBlendOperation( blendEquation )
  48851. };
  48852. alpha = {
  48853. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  48854. dstFactor: this._getBlendFactor( blendDstAlpha ),
  48855. operation: this._getBlendOperation( blendEquationAlpha )
  48856. };
  48857. } else {
  48858. const premultipliedAlpha = material.premultipliedAlpha;
  48859. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  48860. color = {
  48861. srcFactor: srcRGB,
  48862. dstFactor: dstRGB,
  48863. operation: GPUBlendOperation.Add
  48864. };
  48865. alpha = {
  48866. srcFactor: srcAlpha,
  48867. dstFactor: dstAlpha,
  48868. operation: GPUBlendOperation.Add
  48869. };
  48870. };
  48871. if ( premultipliedAlpha ) {
  48872. switch ( blending ) {
  48873. case NormalBlending:
  48874. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  48875. break;
  48876. case AdditiveBlending:
  48877. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  48878. break;
  48879. case SubtractiveBlending:
  48880. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  48881. break;
  48882. case MultiplyBlending:
  48883. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  48884. break;
  48885. }
  48886. } else {
  48887. switch ( blending ) {
  48888. case NormalBlending:
  48889. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  48890. break;
  48891. case AdditiveBlending:
  48892. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  48893. break;
  48894. case SubtractiveBlending:
  48895. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  48896. break;
  48897. case MultiplyBlending:
  48898. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  48899. break;
  48900. }
  48901. }
  48902. }
  48903. if ( color !== undefined && alpha !== undefined ) {
  48904. return { color, alpha };
  48905. } else {
  48906. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  48907. }
  48908. }
  48909. /**
  48910. * Returns the GPU blend factor which is required for the pipeline creation.
  48911. *
  48912. * @private
  48913. * @param {number} blend - The blend factor as a three.js constant.
  48914. * @return {string} The GPU blend factor.
  48915. */
  48916. _getBlendFactor( blend ) {
  48917. let blendFactor;
  48918. switch ( blend ) {
  48919. case ZeroFactor:
  48920. blendFactor = GPUBlendFactor.Zero;
  48921. break;
  48922. case OneFactor:
  48923. blendFactor = GPUBlendFactor.One;
  48924. break;
  48925. case SrcColorFactor:
  48926. blendFactor = GPUBlendFactor.Src;
  48927. break;
  48928. case OneMinusSrcColorFactor:
  48929. blendFactor = GPUBlendFactor.OneMinusSrc;
  48930. break;
  48931. case SrcAlphaFactor:
  48932. blendFactor = GPUBlendFactor.SrcAlpha;
  48933. break;
  48934. case OneMinusSrcAlphaFactor:
  48935. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  48936. break;
  48937. case DstColorFactor:
  48938. blendFactor = GPUBlendFactor.Dst;
  48939. break;
  48940. case OneMinusDstColorFactor:
  48941. blendFactor = GPUBlendFactor.OneMinusDstColor;
  48942. break;
  48943. case DstAlphaFactor:
  48944. blendFactor = GPUBlendFactor.DstAlpha;
  48945. break;
  48946. case OneMinusDstAlphaFactor:
  48947. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  48948. break;
  48949. case SrcAlphaSaturateFactor:
  48950. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  48951. break;
  48952. case BlendColorFactor:
  48953. blendFactor = GPUBlendFactor.Constant;
  48954. break;
  48955. case OneMinusBlendColorFactor:
  48956. blendFactor = GPUBlendFactor.OneMinusConstant;
  48957. break;
  48958. default:
  48959. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  48960. }
  48961. return blendFactor;
  48962. }
  48963. /**
  48964. * Returns the GPU stencil compare function which is required for the pipeline creation.
  48965. *
  48966. * @private
  48967. * @param {Material} material - The material.
  48968. * @return {string} The GPU stencil compare function.
  48969. */
  48970. _getStencilCompare( material ) {
  48971. let stencilCompare;
  48972. const stencilFunc = material.stencilFunc;
  48973. switch ( stencilFunc ) {
  48974. case NeverStencilFunc:
  48975. stencilCompare = GPUCompareFunction.Never;
  48976. break;
  48977. case AlwaysStencilFunc:
  48978. stencilCompare = GPUCompareFunction.Always;
  48979. break;
  48980. case LessStencilFunc:
  48981. stencilCompare = GPUCompareFunction.Less;
  48982. break;
  48983. case LessEqualStencilFunc:
  48984. stencilCompare = GPUCompareFunction.LessEqual;
  48985. break;
  48986. case EqualStencilFunc:
  48987. stencilCompare = GPUCompareFunction.Equal;
  48988. break;
  48989. case GreaterEqualStencilFunc:
  48990. stencilCompare = GPUCompareFunction.GreaterEqual;
  48991. break;
  48992. case GreaterStencilFunc:
  48993. stencilCompare = GPUCompareFunction.Greater;
  48994. break;
  48995. case NotEqualStencilFunc:
  48996. stencilCompare = GPUCompareFunction.NotEqual;
  48997. break;
  48998. default:
  48999. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  49000. }
  49001. return stencilCompare;
  49002. }
  49003. /**
  49004. * Returns the GPU stencil operation which is required for the pipeline creation.
  49005. *
  49006. * @private
  49007. * @param {number} op - A three.js constant defining the stencil operation.
  49008. * @return {string} The GPU stencil operation.
  49009. */
  49010. _getStencilOperation( op ) {
  49011. let stencilOperation;
  49012. switch ( op ) {
  49013. case KeepStencilOp:
  49014. stencilOperation = GPUStencilOperation.Keep;
  49015. break;
  49016. case ZeroStencilOp:
  49017. stencilOperation = GPUStencilOperation.Zero;
  49018. break;
  49019. case ReplaceStencilOp:
  49020. stencilOperation = GPUStencilOperation.Replace;
  49021. break;
  49022. case InvertStencilOp:
  49023. stencilOperation = GPUStencilOperation.Invert;
  49024. break;
  49025. case IncrementStencilOp:
  49026. stencilOperation = GPUStencilOperation.IncrementClamp;
  49027. break;
  49028. case DecrementStencilOp:
  49029. stencilOperation = GPUStencilOperation.DecrementClamp;
  49030. break;
  49031. case IncrementWrapStencilOp:
  49032. stencilOperation = GPUStencilOperation.IncrementWrap;
  49033. break;
  49034. case DecrementWrapStencilOp:
  49035. stencilOperation = GPUStencilOperation.DecrementWrap;
  49036. break;
  49037. default:
  49038. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  49039. }
  49040. return stencilOperation;
  49041. }
  49042. /**
  49043. * Returns the GPU blend operation which is required for the pipeline creation.
  49044. *
  49045. * @private
  49046. * @param {number} blendEquation - A three.js constant defining the blend equation.
  49047. * @return {string} The GPU blend operation.
  49048. */
  49049. _getBlendOperation( blendEquation ) {
  49050. let blendOperation;
  49051. switch ( blendEquation ) {
  49052. case AddEquation:
  49053. blendOperation = GPUBlendOperation.Add;
  49054. break;
  49055. case SubtractEquation:
  49056. blendOperation = GPUBlendOperation.Subtract;
  49057. break;
  49058. case ReverseSubtractEquation:
  49059. blendOperation = GPUBlendOperation.ReverseSubtract;
  49060. break;
  49061. case MinEquation:
  49062. blendOperation = GPUBlendOperation.Min;
  49063. break;
  49064. case MaxEquation:
  49065. blendOperation = GPUBlendOperation.Max;
  49066. break;
  49067. default:
  49068. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  49069. }
  49070. return blendOperation;
  49071. }
  49072. /**
  49073. * Returns the primitive state as a descriptor object required
  49074. * for the pipeline creation.
  49075. *
  49076. * @private
  49077. * @param {Object3D} object - The 3D object.
  49078. * @param {BufferGeometry} geometry - The geometry.
  49079. * @param {Material} material - The material.
  49080. * @return {Object} The primitive state.
  49081. */
  49082. _getPrimitiveState( object, geometry, material ) {
  49083. const descriptor = {};
  49084. const utils = this.backend.utils;
  49085. descriptor.topology = utils.getPrimitiveTopology( object, material );
  49086. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  49087. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  49088. }
  49089. switch ( material.side ) {
  49090. case FrontSide:
  49091. descriptor.frontFace = GPUFrontFace.CCW;
  49092. descriptor.cullMode = GPUCullMode.Back;
  49093. break;
  49094. case BackSide:
  49095. descriptor.frontFace = GPUFrontFace.CCW;
  49096. descriptor.cullMode = GPUCullMode.Front;
  49097. break;
  49098. case DoubleSide:
  49099. descriptor.frontFace = GPUFrontFace.CCW;
  49100. descriptor.cullMode = GPUCullMode.None;
  49101. break;
  49102. default:
  49103. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  49104. break;
  49105. }
  49106. return descriptor;
  49107. }
  49108. /**
  49109. * Returns the GPU color write mask which is required for the pipeline creation.
  49110. *
  49111. * @private
  49112. * @param {Material} material - The material.
  49113. * @return {string} The GPU color write mask.
  49114. */
  49115. _getColorWriteMask( material ) {
  49116. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  49117. }
  49118. /**
  49119. * Returns the GPU depth compare function which is required for the pipeline creation.
  49120. *
  49121. * @private
  49122. * @param {Material} material - The material.
  49123. * @return {string} The GPU depth compare function.
  49124. */
  49125. _getDepthCompare( material ) {
  49126. let depthCompare;
  49127. if ( material.depthTest === false ) {
  49128. depthCompare = GPUCompareFunction.Always;
  49129. } else {
  49130. const depthFunc = material.depthFunc;
  49131. switch ( depthFunc ) {
  49132. case NeverDepth:
  49133. depthCompare = GPUCompareFunction.Never;
  49134. break;
  49135. case AlwaysDepth:
  49136. depthCompare = GPUCompareFunction.Always;
  49137. break;
  49138. case LessDepth:
  49139. depthCompare = GPUCompareFunction.Less;
  49140. break;
  49141. case LessEqualDepth:
  49142. depthCompare = GPUCompareFunction.LessEqual;
  49143. break;
  49144. case EqualDepth:
  49145. depthCompare = GPUCompareFunction.Equal;
  49146. break;
  49147. case GreaterEqualDepth:
  49148. depthCompare = GPUCompareFunction.GreaterEqual;
  49149. break;
  49150. case GreaterDepth:
  49151. depthCompare = GPUCompareFunction.Greater;
  49152. break;
  49153. case NotEqualDepth:
  49154. depthCompare = GPUCompareFunction.NotEqual;
  49155. break;
  49156. default:
  49157. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  49158. }
  49159. }
  49160. return depthCompare;
  49161. }
  49162. }
  49163. /**
  49164. * Manages a pool of WebGPU timestamp queries for performance measurement.
  49165. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  49166. *
  49167. * @augments TimestampQueryPool
  49168. */
  49169. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  49170. /**
  49171. * Creates a new WebGPU timestamp query pool.
  49172. *
  49173. * @param {GPUDevice} device - The WebGPU device to create queries on.
  49174. * @param {string} type - The type identifier for this query pool.
  49175. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  49176. */
  49177. constructor( device, type, maxQueries = 2048 ) {
  49178. super( maxQueries );
  49179. this.device = device;
  49180. this.type = type;
  49181. this.querySet = this.device.createQuerySet( {
  49182. type: 'timestamp',
  49183. count: this.maxQueries,
  49184. label: `queryset_global_timestamp_${type}`
  49185. } );
  49186. const bufferSize = this.maxQueries * 8;
  49187. this.resolveBuffer = this.device.createBuffer( {
  49188. label: `buffer_timestamp_resolve_${type}`,
  49189. size: bufferSize,
  49190. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  49191. } );
  49192. this.resultBuffer = this.device.createBuffer( {
  49193. label: `buffer_timestamp_result_${type}`,
  49194. size: bufferSize,
  49195. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49196. } );
  49197. }
  49198. /**
  49199. * Allocates a pair of queries for a given render context.
  49200. *
  49201. * @param {Object} renderContext - The render context to allocate queries for.
  49202. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  49203. */
  49204. allocateQueriesForContext( renderContext ) {
  49205. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  49206. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  49207. warnOnce( `WebGPUTimestampQueryPool [${ this.type }]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${ this.type.toUpperCase() } ).` );
  49208. return null;
  49209. }
  49210. const baseOffset = this.currentQueryIndex;
  49211. this.currentQueryIndex += 2;
  49212. this.queryOffsets.set( renderContext.id, baseOffset );
  49213. return baseOffset;
  49214. }
  49215. /**
  49216. * Asynchronously resolves all pending queries and returns the total duration.
  49217. * If there's already a pending resolve operation, returns that promise instead.
  49218. *
  49219. * @async
  49220. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  49221. */
  49222. async resolveQueriesAsync() {
  49223. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  49224. return this.lastValue;
  49225. }
  49226. if ( this.pendingResolve ) {
  49227. return this.pendingResolve;
  49228. }
  49229. this.pendingResolve = this._resolveQueries();
  49230. try {
  49231. const result = await this.pendingResolve;
  49232. return result;
  49233. } finally {
  49234. this.pendingResolve = null;
  49235. }
  49236. }
  49237. /**
  49238. * Internal method to resolve queries and calculate total duration.
  49239. *
  49240. * @async
  49241. * @private
  49242. * @returns {Promise<number>} The total duration in milliseconds.
  49243. */
  49244. async _resolveQueries() {
  49245. if ( this.isDisposed ) {
  49246. return this.lastValue;
  49247. }
  49248. try {
  49249. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49250. return this.lastValue;
  49251. }
  49252. const currentOffsets = new Map( this.queryOffsets );
  49253. const queryCount = this.currentQueryIndex;
  49254. const bytesUsed = queryCount * 8;
  49255. // Reset state before GPU work
  49256. this.currentQueryIndex = 0;
  49257. this.queryOffsets.clear();
  49258. const commandEncoder = this.device.createCommandEncoder();
  49259. commandEncoder.resolveQuerySet(
  49260. this.querySet,
  49261. 0,
  49262. queryCount,
  49263. this.resolveBuffer,
  49264. 0
  49265. );
  49266. commandEncoder.copyBufferToBuffer(
  49267. this.resolveBuffer,
  49268. 0,
  49269. this.resultBuffer,
  49270. 0,
  49271. bytesUsed
  49272. );
  49273. const commandBuffer = commandEncoder.finish();
  49274. this.device.queue.submit( [ commandBuffer ] );
  49275. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49276. return this.lastValue;
  49277. }
  49278. // Create and track the mapping operation
  49279. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  49280. if ( this.isDisposed ) {
  49281. if ( this.resultBuffer.mapState === 'mapped' ) {
  49282. this.resultBuffer.unmap();
  49283. }
  49284. return this.lastValue;
  49285. }
  49286. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  49287. let totalDuration = 0;
  49288. for ( const [ , baseOffset ] of currentOffsets ) {
  49289. const startTime = times[ baseOffset ];
  49290. const endTime = times[ baseOffset + 1 ];
  49291. const duration = Number( endTime - startTime ) / 1e6;
  49292. totalDuration += duration;
  49293. }
  49294. this.resultBuffer.unmap();
  49295. this.lastValue = totalDuration;
  49296. return totalDuration;
  49297. } catch ( error ) {
  49298. console.error( 'Error resolving queries:', error );
  49299. if ( this.resultBuffer.mapState === 'mapped' ) {
  49300. this.resultBuffer.unmap();
  49301. }
  49302. return this.lastValue;
  49303. }
  49304. }
  49305. /**
  49306. * Dispose of the query pool.
  49307. *
  49308. * @async
  49309. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  49310. */
  49311. async dispose() {
  49312. if ( this.isDisposed ) {
  49313. return;
  49314. }
  49315. this.isDisposed = true;
  49316. // Wait for pending resolve operation
  49317. if ( this.pendingResolve ) {
  49318. try {
  49319. await this.pendingResolve;
  49320. } catch ( error ) {
  49321. console.error( 'Error waiting for pending resolve:', error );
  49322. }
  49323. }
  49324. // Ensure buffer is unmapped before destroying
  49325. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  49326. try {
  49327. this.resultBuffer.unmap();
  49328. } catch ( error ) {
  49329. console.error( 'Error unmapping buffer:', error );
  49330. }
  49331. }
  49332. // Destroy resources
  49333. if ( this.querySet ) {
  49334. this.querySet.destroy();
  49335. this.querySet = null;
  49336. }
  49337. if ( this.resolveBuffer ) {
  49338. this.resolveBuffer.destroy();
  49339. this.resolveBuffer = null;
  49340. }
  49341. if ( this.resultBuffer ) {
  49342. this.resultBuffer.destroy();
  49343. this.resultBuffer = null;
  49344. }
  49345. this.queryOffsets.clear();
  49346. this.pendingResolve = null;
  49347. }
  49348. }
  49349. /*// debugger tools
  49350. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  49351. //*/
  49352. /**
  49353. * A backend implementation targeting WebGPU.
  49354. *
  49355. * @private
  49356. * @augments Backend
  49357. */
  49358. class WebGPUBackend extends Backend {
  49359. /**
  49360. * WebGPUBackend options.
  49361. *
  49362. * @typedef {Object} WebGPUBackend~Options
  49363. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49364. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49365. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  49366. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49367. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49368. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49369. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  49370. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49371. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  49372. * @property {string} [powerPreference=undefined] - The power preference.
  49373. * @property {Object} [requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  49374. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  49375. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  49376. */
  49377. /**
  49378. * Constructs a new WebGPU backend.
  49379. *
  49380. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  49381. */
  49382. constructor( parameters = {} ) {
  49383. super( parameters );
  49384. /**
  49385. * This flag can be used for type testing.
  49386. *
  49387. * @type {boolean}
  49388. * @readonly
  49389. * @default true
  49390. */
  49391. this.isWebGPUBackend = true;
  49392. // some parameters require default values other than "undefined"
  49393. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  49394. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  49395. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  49396. /**
  49397. * Indicates whether the backend is in compatibility mode or not.
  49398. * @type {boolean}
  49399. * @default false
  49400. */
  49401. this.compatibilityMode = this.parameters.compatibilityMode;
  49402. /**
  49403. * A reference to the device.
  49404. *
  49405. * @type {?GPUDevice}
  49406. * @default null
  49407. */
  49408. this.device = null;
  49409. /**
  49410. * A reference to the context.
  49411. *
  49412. * @type {?GPUCanvasContext}
  49413. * @default null
  49414. */
  49415. this.context = null;
  49416. /**
  49417. * A reference to the color attachment of the default framebuffer.
  49418. *
  49419. * @type {?GPUTexture}
  49420. * @default null
  49421. */
  49422. this.colorBuffer = null;
  49423. /**
  49424. * A reference to the default render pass descriptor.
  49425. *
  49426. * @type {?Object}
  49427. * @default null
  49428. */
  49429. this.defaultRenderPassdescriptor = null;
  49430. /**
  49431. * A reference to a backend module holding common utility functions.
  49432. *
  49433. * @type {WebGPUUtils}
  49434. */
  49435. this.utils = new WebGPUUtils( this );
  49436. /**
  49437. * A reference to a backend module holding shader attribute-related
  49438. * utility functions.
  49439. *
  49440. * @type {WebGPUAttributeUtils}
  49441. */
  49442. this.attributeUtils = new WebGPUAttributeUtils( this );
  49443. /**
  49444. * A reference to a backend module holding shader binding-related
  49445. * utility functions.
  49446. *
  49447. * @type {WebGPUBindingUtils}
  49448. */
  49449. this.bindingUtils = new WebGPUBindingUtils( this );
  49450. /**
  49451. * A reference to a backend module holding shader pipeline-related
  49452. * utility functions.
  49453. *
  49454. * @type {WebGPUPipelineUtils}
  49455. */
  49456. this.pipelineUtils = new WebGPUPipelineUtils( this );
  49457. /**
  49458. * A reference to a backend module holding shader texture-related
  49459. * utility functions.
  49460. *
  49461. * @type {WebGPUTextureUtils}
  49462. */
  49463. this.textureUtils = new WebGPUTextureUtils( this );
  49464. /**
  49465. * A map that manages the resolve buffers for occlusion queries.
  49466. *
  49467. * @type {Map<number,GPUBuffer>}
  49468. */
  49469. this.occludedResolveCache = new Map();
  49470. }
  49471. /**
  49472. * Initializes the backend so it is ready for usage.
  49473. *
  49474. * @async
  49475. * @param {Renderer} renderer - The renderer.
  49476. * @return {Promise} A Promise that resolves when the backend has been initialized.
  49477. */
  49478. async init( renderer ) {
  49479. await super.init( renderer );
  49480. //
  49481. const parameters = this.parameters;
  49482. // create the device if it is not passed with parameters
  49483. let device;
  49484. if ( parameters.device === undefined ) {
  49485. const adapterOptions = {
  49486. powerPreference: parameters.powerPreference,
  49487. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  49488. };
  49489. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  49490. if ( adapter === null ) {
  49491. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  49492. }
  49493. // feature support
  49494. const features = Object.values( GPUFeatureName );
  49495. const supportedFeatures = [];
  49496. for ( const name of features ) {
  49497. if ( adapter.features.has( name ) ) {
  49498. supportedFeatures.push( name );
  49499. }
  49500. }
  49501. const deviceDescriptor = {
  49502. requiredFeatures: supportedFeatures,
  49503. requiredLimits: parameters.requiredLimits
  49504. };
  49505. device = await adapter.requestDevice( deviceDescriptor );
  49506. } else {
  49507. device = parameters.device;
  49508. }
  49509. device.lost.then( ( info ) => {
  49510. const deviceLossInfo = {
  49511. api: 'WebGPU',
  49512. message: info.message || 'Unknown reason',
  49513. reason: info.reason || null,
  49514. originalEvent: info
  49515. };
  49516. renderer.onDeviceLost( deviceLossInfo );
  49517. } );
  49518. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  49519. this.device = device;
  49520. this.context = context;
  49521. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  49522. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  49523. this.context.configure( {
  49524. device: this.device,
  49525. format: this.utils.getPreferredCanvasFormat(),
  49526. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  49527. alphaMode: alphaMode
  49528. } );
  49529. this.updateSize();
  49530. }
  49531. /**
  49532. * The coordinate system of the backend.
  49533. *
  49534. * @type {number}
  49535. * @readonly
  49536. */
  49537. get coordinateSystem() {
  49538. return WebGPUCoordinateSystem;
  49539. }
  49540. /**
  49541. * This method performs a readback operation by moving buffer data from
  49542. * a storage buffer attribute from the GPU to the CPU.
  49543. *
  49544. * @async
  49545. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  49546. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  49547. */
  49548. async getArrayBufferAsync( attribute ) {
  49549. return await this.attributeUtils.getArrayBufferAsync( attribute );
  49550. }
  49551. /**
  49552. * Returns the backend's rendering context.
  49553. *
  49554. * @return {GPUCanvasContext} The rendering context.
  49555. */
  49556. getContext() {
  49557. return this.context;
  49558. }
  49559. /**
  49560. * Returns the default render pass descriptor.
  49561. *
  49562. * In WebGPU, the default framebuffer must be configured
  49563. * like custom framebuffers so the backend needs a render
  49564. * pass descriptor even when rendering directly to screen.
  49565. *
  49566. * @private
  49567. * @return {Object} The render pass descriptor.
  49568. */
  49569. _getDefaultRenderPassDescriptor() {
  49570. let descriptor = this.defaultRenderPassdescriptor;
  49571. if ( descriptor === null ) {
  49572. const renderer = this.renderer;
  49573. descriptor = {
  49574. colorAttachments: [ {
  49575. view: null
  49576. } ],
  49577. };
  49578. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  49579. descriptor.depthStencilAttachment = {
  49580. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  49581. };
  49582. }
  49583. const colorAttachment = descriptor.colorAttachments[ 0 ];
  49584. if ( this.renderer.samples > 0 ) {
  49585. colorAttachment.view = this.colorBuffer.createView();
  49586. } else {
  49587. colorAttachment.resolveTarget = undefined;
  49588. }
  49589. this.defaultRenderPassdescriptor = descriptor;
  49590. }
  49591. const colorAttachment = descriptor.colorAttachments[ 0 ];
  49592. if ( this.renderer.samples > 0 ) {
  49593. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  49594. } else {
  49595. colorAttachment.view = this.context.getCurrentTexture().createView();
  49596. }
  49597. return descriptor;
  49598. }
  49599. /**
  49600. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  49601. *
  49602. * @param {RenderContext} renderContext - The render context.
  49603. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  49604. *
  49605. * @private
  49606. */
  49607. _isRenderCameraDepthArray( renderContext ) {
  49608. return renderContext.depthTexture && renderContext.depthTexture.isDepthArrayTexture && renderContext.camera.isArrayCamera;
  49609. }
  49610. /**
  49611. * Returns the render pass descriptor for the given render context.
  49612. *
  49613. * @private
  49614. * @param {RenderContext} renderContext - The render context.
  49615. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  49616. * @return {Object} The render pass descriptor.
  49617. */
  49618. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  49619. const renderTarget = renderContext.renderTarget;
  49620. const renderTargetData = this.get( renderTarget );
  49621. let descriptors = renderTargetData.descriptors;
  49622. if ( descriptors === undefined ||
  49623. renderTargetData.width !== renderTarget.width ||
  49624. renderTargetData.height !== renderTarget.height ||
  49625. renderTargetData.dimensions !== renderTarget.dimensions ||
  49626. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  49627. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  49628. renderTargetData.samples !== renderTarget.samples
  49629. ) {
  49630. descriptors = {};
  49631. renderTargetData.descriptors = descriptors;
  49632. // dispose
  49633. const onDispose = () => {
  49634. renderTarget.removeEventListener( 'dispose', onDispose );
  49635. this.delete( renderTarget );
  49636. };
  49637. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  49638. renderTarget.addEventListener( 'dispose', onDispose );
  49639. }
  49640. }
  49641. const cacheKey = renderContext.getCacheKey();
  49642. let descriptorBase = descriptors[ cacheKey ];
  49643. if ( descriptorBase === undefined ) {
  49644. const textures = renderContext.textures;
  49645. const textureViews = [];
  49646. let sliceIndex;
  49647. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  49648. for ( let i = 0; i < textures.length; i ++ ) {
  49649. const textureData = this.get( textures[ i ] );
  49650. const viewDescriptor = {
  49651. label: `colorAttachment_${ i }`,
  49652. baseMipLevel: renderContext.activeMipmapLevel,
  49653. mipLevelCount: 1,
  49654. baseArrayLayer: renderContext.activeCubeFace,
  49655. arrayLayerCount: 1,
  49656. dimension: GPUTextureViewDimension.TwoD
  49657. };
  49658. if ( renderTarget.isRenderTarget3D ) {
  49659. sliceIndex = renderContext.activeCubeFace;
  49660. viewDescriptor.baseArrayLayer = 0;
  49661. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  49662. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  49663. } else if ( renderTarget.isRenderTargetArray ) {
  49664. if ( isRenderCameraDepthArray === true ) {
  49665. const cameras = renderContext.camera.cameras;
  49666. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  49667. const layerViewDescriptor = {
  49668. ...viewDescriptor,
  49669. baseArrayLayer: layer,
  49670. arrayLayerCount: 1,
  49671. dimension: GPUTextureViewDimension.TwoD
  49672. };
  49673. const textureView = textureData.texture.createView( layerViewDescriptor );
  49674. textureViews.push( {
  49675. view: textureView,
  49676. resolveTarget: undefined,
  49677. depthSlice: undefined
  49678. } );
  49679. }
  49680. } else {
  49681. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  49682. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  49683. }
  49684. }
  49685. if ( isRenderCameraDepthArray !== true ) {
  49686. const textureView = textureData.texture.createView( viewDescriptor );
  49687. let view, resolveTarget;
  49688. if ( textureData.msaaTexture !== undefined ) {
  49689. view = textureData.msaaTexture.createView();
  49690. resolveTarget = textureView;
  49691. } else {
  49692. view = textureView;
  49693. resolveTarget = undefined;
  49694. }
  49695. textureViews.push( {
  49696. view,
  49697. resolveTarget,
  49698. depthSlice: sliceIndex
  49699. } );
  49700. }
  49701. }
  49702. descriptorBase = { textureViews };
  49703. if ( renderContext.depth ) {
  49704. const depthTextureData = this.get( renderContext.depthTexture );
  49705. const options = {};
  49706. if ( renderContext.depthTexture.isDepthArrayTexture ) {
  49707. options.dimension = GPUTextureViewDimension.TwoD;
  49708. options.arrayLayerCount = 1;
  49709. options.baseArrayLayer = renderContext.activeCubeFace;
  49710. }
  49711. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  49712. }
  49713. descriptors[ cacheKey ] = descriptorBase;
  49714. renderTargetData.width = renderTarget.width;
  49715. renderTargetData.height = renderTarget.height;
  49716. renderTargetData.samples = renderTarget.samples;
  49717. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  49718. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  49719. renderTargetData.dimensions = renderTarget.dimensions;
  49720. }
  49721. const descriptor = {
  49722. colorAttachments: []
  49723. };
  49724. // Apply dynamic properties to cached views
  49725. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  49726. const viewInfo = descriptorBase.textureViews[ i ];
  49727. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  49728. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  49729. clearValue = colorAttachmentsConfig.clearValue;
  49730. }
  49731. descriptor.colorAttachments.push( {
  49732. view: viewInfo.view,
  49733. depthSlice: viewInfo.depthSlice,
  49734. resolveTarget: viewInfo.resolveTarget,
  49735. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  49736. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  49737. clearValue: clearValue
  49738. } );
  49739. }
  49740. if ( descriptorBase.depthStencilView ) {
  49741. descriptor.depthStencilAttachment = {
  49742. view: descriptorBase.depthStencilView
  49743. };
  49744. }
  49745. return descriptor;
  49746. }
  49747. /**
  49748. * This method is executed at the beginning of a render call and prepares
  49749. * the WebGPU state for upcoming render calls
  49750. *
  49751. * @param {RenderContext} renderContext - The render context.
  49752. */
  49753. beginRender( renderContext ) {
  49754. const renderContextData = this.get( renderContext );
  49755. const device = this.device;
  49756. const occlusionQueryCount = renderContext.occlusionQueryCount;
  49757. let occlusionQuerySet;
  49758. if ( occlusionQueryCount > 0 ) {
  49759. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  49760. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  49761. // Get a reference to the array of objects with queries. The renderContextData property
  49762. // can be changed by another render pass before the buffer.mapAsyc() completes.
  49763. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  49764. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  49765. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  49766. //
  49767. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  49768. renderContextData.occlusionQuerySet = occlusionQuerySet;
  49769. renderContextData.occlusionQueryIndex = 0;
  49770. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  49771. renderContextData.lastOcclusionObject = null;
  49772. }
  49773. let descriptor;
  49774. if ( renderContext.textures === null ) {
  49775. descriptor = this._getDefaultRenderPassDescriptor();
  49776. } else {
  49777. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  49778. }
  49779. this.initTimestampQuery( renderContext, descriptor );
  49780. descriptor.occlusionQuerySet = occlusionQuerySet;
  49781. const depthStencilAttachment = descriptor.depthStencilAttachment;
  49782. if ( renderContext.textures !== null ) {
  49783. const colorAttachments = descriptor.colorAttachments;
  49784. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  49785. const colorAttachment = colorAttachments[ i ];
  49786. if ( renderContext.clearColor ) {
  49787. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  49788. colorAttachment.loadOp = GPULoadOp.Clear;
  49789. } else {
  49790. colorAttachment.loadOp = GPULoadOp.Load;
  49791. }
  49792. colorAttachment.storeOp = GPUStoreOp.Store;
  49793. }
  49794. } else {
  49795. const colorAttachment = descriptor.colorAttachments[ 0 ];
  49796. if ( renderContext.clearColor ) {
  49797. colorAttachment.clearValue = renderContext.clearColorValue;
  49798. colorAttachment.loadOp = GPULoadOp.Clear;
  49799. } else {
  49800. colorAttachment.loadOp = GPULoadOp.Load;
  49801. }
  49802. colorAttachment.storeOp = GPUStoreOp.Store;
  49803. }
  49804. //
  49805. if ( renderContext.depth ) {
  49806. if ( renderContext.clearDepth ) {
  49807. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  49808. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  49809. } else {
  49810. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  49811. }
  49812. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  49813. }
  49814. if ( renderContext.stencil ) {
  49815. if ( renderContext.clearStencil ) {
  49816. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  49817. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  49818. } else {
  49819. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  49820. }
  49821. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  49822. }
  49823. //
  49824. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  49825. // shadow arrays - prepare bundle encoders for each camera in an array camera
  49826. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  49827. const cameras = renderContext.camera.cameras;
  49828. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  49829. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  49830. } else {
  49831. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  49832. }
  49833. // Create bundle encoders for each layer
  49834. renderContextData.bundleEncoders = [];
  49835. renderContextData.bundleSets = [];
  49836. // Create separate bundle encoders for each camera in the array
  49837. for ( let i = 0; i < cameras.length; i ++ ) {
  49838. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  49839. renderContext,
  49840. 'renderBundleArrayCamera_' + i
  49841. );
  49842. // Initialize state tracking for this bundle
  49843. const bundleSets = {
  49844. attributes: {},
  49845. bindingGroups: [],
  49846. pipeline: null,
  49847. index: null
  49848. };
  49849. renderContextData.bundleEncoders.push( bundleEncoder );
  49850. renderContextData.bundleSets.push( bundleSets );
  49851. }
  49852. // We'll complete the bundles in finishRender
  49853. renderContextData.currentPass = null;
  49854. } else {
  49855. const currentPass = encoder.beginRenderPass( descriptor );
  49856. renderContextData.currentPass = currentPass;
  49857. if ( renderContext.viewport ) {
  49858. this.updateViewport( renderContext );
  49859. }
  49860. if ( renderContext.scissor ) {
  49861. const { x, y, width, height } = renderContext.scissorValue;
  49862. currentPass.setScissorRect( x, y, width, height );
  49863. }
  49864. }
  49865. //
  49866. renderContextData.descriptor = descriptor;
  49867. renderContextData.encoder = encoder;
  49868. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  49869. renderContextData.renderBundles = [];
  49870. }
  49871. /**
  49872. * This method creates layer descriptors for each camera in an array camera
  49873. * to prepare for rendering to a depth array texture.
  49874. *
  49875. * @param {RenderContext} renderContext - The render context.
  49876. * @param {Object} renderContextData - The render context data.
  49877. * @param {Object} descriptor - The render pass descriptor.
  49878. * @param {ArrayCamera} cameras - The array camera.
  49879. *
  49880. * @private
  49881. */
  49882. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  49883. const depthStencilAttachment = descriptor.depthStencilAttachment;
  49884. renderContextData.layerDescriptors = [];
  49885. const depthTextureData = this.get( renderContext.depthTexture );
  49886. if ( ! depthTextureData.viewCache ) {
  49887. depthTextureData.viewCache = [];
  49888. }
  49889. for ( let i = 0; i < cameras.length; i ++ ) {
  49890. const layerDescriptor = {
  49891. ...descriptor,
  49892. colorAttachments: [ {
  49893. ...descriptor.colorAttachments[ 0 ],
  49894. view: descriptor.colorAttachments[ i ].view
  49895. } ]
  49896. };
  49897. if ( descriptor.depthStencilAttachment ) {
  49898. const layerIndex = i;
  49899. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  49900. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  49901. dimension: GPUTextureViewDimension.TwoD,
  49902. baseArrayLayer: i,
  49903. arrayLayerCount: 1
  49904. } );
  49905. }
  49906. layerDescriptor.depthStencilAttachment = {
  49907. view: depthTextureData.viewCache[ layerIndex ],
  49908. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  49909. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  49910. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  49911. };
  49912. if ( renderContext.stencil ) {
  49913. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  49914. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  49915. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  49916. }
  49917. } else {
  49918. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  49919. }
  49920. renderContextData.layerDescriptors.push( layerDescriptor );
  49921. }
  49922. }
  49923. /**
  49924. * This method updates the layer descriptors for each camera in an array camera
  49925. * to prepare for rendering to a depth array texture.
  49926. *
  49927. * @param {RenderContext} renderContext - The render context.
  49928. * @param {Object} renderContextData - The render context data.
  49929. * @param {ArrayCamera} cameras - The array camera.
  49930. *
  49931. */
  49932. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  49933. for ( let i = 0; i < cameras.length; i ++ ) {
  49934. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  49935. if ( layerDescriptor.depthStencilAttachment ) {
  49936. const depthAttachment = layerDescriptor.depthStencilAttachment;
  49937. if ( renderContext.depth ) {
  49938. if ( renderContext.clearDepth ) {
  49939. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  49940. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  49941. } else {
  49942. depthAttachment.depthLoadOp = GPULoadOp.Load;
  49943. }
  49944. }
  49945. if ( renderContext.stencil ) {
  49946. if ( renderContext.clearStencil ) {
  49947. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  49948. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  49949. } else {
  49950. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  49951. }
  49952. }
  49953. }
  49954. }
  49955. }
  49956. /**
  49957. * This method is executed at the end of a render call and finalizes work
  49958. * after draw calls.
  49959. *
  49960. * @param {RenderContext} renderContext - The render context.
  49961. */
  49962. finishRender( renderContext ) {
  49963. const renderContextData = this.get( renderContext );
  49964. const occlusionQueryCount = renderContext.occlusionQueryCount;
  49965. if ( renderContextData.renderBundles.length > 0 ) {
  49966. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  49967. }
  49968. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  49969. renderContextData.currentPass.endOcclusionQuery();
  49970. }
  49971. // shadow arrays - Execute bundles for each layer
  49972. const encoder = renderContextData.encoder;
  49973. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  49974. const bundles = [];
  49975. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  49976. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  49977. bundles.push( bundleEncoder.finish() );
  49978. }
  49979. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  49980. if ( i < bundles.length ) {
  49981. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  49982. const renderPass = encoder.beginRenderPass( layerDescriptor );
  49983. if ( renderContext.viewport ) {
  49984. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  49985. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  49986. }
  49987. if ( renderContext.scissor ) {
  49988. const { x, y, width, height } = renderContext.scissorValue;
  49989. renderPass.setScissorRect( x, y, width, height );
  49990. }
  49991. renderPass.executeBundles( [ bundles[ i ] ] );
  49992. renderPass.end();
  49993. }
  49994. }
  49995. } else if ( renderContextData.currentPass ) {
  49996. renderContextData.currentPass.end();
  49997. }
  49998. if ( occlusionQueryCount > 0 ) {
  49999. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  50000. //
  50001. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  50002. if ( queryResolveBuffer === undefined ) {
  50003. queryResolveBuffer = this.device.createBuffer(
  50004. {
  50005. size: bufferSize,
  50006. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50007. }
  50008. );
  50009. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  50010. }
  50011. //
  50012. const readBuffer = this.device.createBuffer(
  50013. {
  50014. size: bufferSize,
  50015. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50016. }
  50017. );
  50018. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  50019. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  50020. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  50021. renderContextData.occlusionQueryBuffer = readBuffer;
  50022. //
  50023. this.resolveOccludedAsync( renderContext );
  50024. }
  50025. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  50026. //
  50027. if ( renderContext.textures !== null ) {
  50028. const textures = renderContext.textures;
  50029. for ( let i = 0; i < textures.length; i ++ ) {
  50030. const texture = textures[ i ];
  50031. if ( texture.generateMipmaps === true ) {
  50032. this.textureUtils.generateMipmaps( texture );
  50033. }
  50034. }
  50035. }
  50036. }
  50037. /**
  50038. * Returns `true` if the given 3D object is fully occluded by other
  50039. * 3D objects in the scene.
  50040. *
  50041. * @param {RenderContext} renderContext - The render context.
  50042. * @param {Object3D} object - The 3D object to test.
  50043. * @return {boolean} Whether the 3D object is fully occluded or not.
  50044. */
  50045. isOccluded( renderContext, object ) {
  50046. const renderContextData = this.get( renderContext );
  50047. return renderContextData.occluded && renderContextData.occluded.has( object );
  50048. }
  50049. /**
  50050. * This method processes the result of occlusion queries and writes it
  50051. * into render context data.
  50052. *
  50053. * @async
  50054. * @param {RenderContext} renderContext - The render context.
  50055. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  50056. */
  50057. async resolveOccludedAsync( renderContext ) {
  50058. const renderContextData = this.get( renderContext );
  50059. // handle occlusion query results
  50060. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  50061. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  50062. const occluded = new WeakSet();
  50063. renderContextData.currentOcclusionQueryObjects = null;
  50064. renderContextData.currentOcclusionQueryBuffer = null;
  50065. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  50066. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  50067. const results = new BigUint64Array( buffer );
  50068. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  50069. if ( results[ i ] === BigInt( 0 ) ) {
  50070. occluded.add( currentOcclusionQueryObjects[ i ] );
  50071. }
  50072. }
  50073. currentOcclusionQueryBuffer.destroy();
  50074. renderContextData.occluded = occluded;
  50075. }
  50076. }
  50077. /**
  50078. * Updates the viewport with the values from the given render context.
  50079. *
  50080. * @param {RenderContext} renderContext - The render context.
  50081. */
  50082. updateViewport( renderContext ) {
  50083. const { currentPass } = this.get( renderContext );
  50084. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50085. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50086. }
  50087. /**
  50088. * Returns the clear color and alpha into a single
  50089. * color object.
  50090. *
  50091. * @return {Color4} The clear color.
  50092. */
  50093. getClearColor() {
  50094. const clearColor = super.getClearColor();
  50095. // only premultiply alpha when alphaMode is "premultiplied"
  50096. if ( this.renderer.alpha === true ) {
  50097. clearColor.r *= clearColor.a;
  50098. clearColor.g *= clearColor.a;
  50099. clearColor.b *= clearColor.a;
  50100. }
  50101. return clearColor;
  50102. }
  50103. /**
  50104. * Performs a clear operation.
  50105. *
  50106. * @param {boolean} color - Whether the color buffer should be cleared or not.
  50107. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  50108. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  50109. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  50110. */
  50111. clear( color, depth, stencil, renderTargetContext = null ) {
  50112. const device = this.device;
  50113. const renderer = this.renderer;
  50114. let colorAttachments = [];
  50115. let depthStencilAttachment;
  50116. let clearValue;
  50117. let supportsDepth;
  50118. let supportsStencil;
  50119. if ( color ) {
  50120. const clearColor = this.getClearColor();
  50121. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  50122. }
  50123. if ( renderTargetContext === null ) {
  50124. supportsDepth = renderer.depth;
  50125. supportsStencil = renderer.stencil;
  50126. const descriptor = this._getDefaultRenderPassDescriptor();
  50127. if ( color ) {
  50128. colorAttachments = descriptor.colorAttachments;
  50129. const colorAttachment = colorAttachments[ 0 ];
  50130. colorAttachment.clearValue = clearValue;
  50131. colorAttachment.loadOp = GPULoadOp.Clear;
  50132. colorAttachment.storeOp = GPUStoreOp.Store;
  50133. }
  50134. if ( supportsDepth || supportsStencil ) {
  50135. depthStencilAttachment = descriptor.depthStencilAttachment;
  50136. }
  50137. } else {
  50138. supportsDepth = renderTargetContext.depth;
  50139. supportsStencil = renderTargetContext.stencil;
  50140. const clearConfig = {
  50141. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  50142. clearValue: color ? clearValue : undefined
  50143. };
  50144. if ( supportsDepth ) {
  50145. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  50146. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  50147. clearConfig.depthStoreOp = GPUStoreOp.Store;
  50148. }
  50149. if ( supportsStencil ) {
  50150. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  50151. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  50152. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  50153. }
  50154. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  50155. colorAttachments = descriptor.colorAttachments;
  50156. depthStencilAttachment = descriptor.depthStencilAttachment;
  50157. }
  50158. if ( supportsDepth && depthStencilAttachment && depthStencilAttachment.depthLoadOp === undefined ) {
  50159. if ( depth ) {
  50160. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50161. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  50162. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50163. } else {
  50164. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50165. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50166. }
  50167. }
  50168. //
  50169. if ( supportsStencil && depthStencilAttachment && depthStencilAttachment.stencilLoadOp === undefined ) {
  50170. if ( stencil ) {
  50171. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50172. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  50173. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50174. } else {
  50175. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50176. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50177. }
  50178. }
  50179. //
  50180. const encoder = device.createCommandEncoder( { label: 'clear' } );
  50181. const currentPass = encoder.beginRenderPass( {
  50182. colorAttachments,
  50183. depthStencilAttachment
  50184. } );
  50185. currentPass.end();
  50186. device.queue.submit( [ encoder.finish() ] );
  50187. }
  50188. // compute
  50189. /**
  50190. * This method is executed at the beginning of a compute call and
  50191. * prepares the state for upcoming compute tasks.
  50192. *
  50193. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50194. */
  50195. beginCompute( computeGroup ) {
  50196. const groupGPU = this.get( computeGroup );
  50197. const descriptor = {
  50198. label: 'computeGroup_' + computeGroup.id
  50199. };
  50200. this.initTimestampQuery( computeGroup, descriptor );
  50201. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  50202. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  50203. }
  50204. /**
  50205. * Executes a compute command for the given compute node.
  50206. *
  50207. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  50208. * @param {Node} computeNode - The compute node.
  50209. * @param {Array<BindGroup>} bindings - The bindings.
  50210. * @param {ComputePipeline} pipeline - The compute pipeline.
  50211. */
  50212. compute( computeGroup, computeNode, bindings, pipeline ) {
  50213. const { passEncoderGPU } = this.get( computeGroup );
  50214. // pipeline
  50215. const pipelineGPU = this.get( pipeline ).pipeline;
  50216. passEncoderGPU.setPipeline( pipelineGPU );
  50217. // bind groups
  50218. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50219. const bindGroup = bindings[ i ];
  50220. const bindingsData = this.get( bindGroup );
  50221. passEncoderGPU.setBindGroup( i, bindingsData.group );
  50222. }
  50223. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  50224. const computeNodeData = this.get( computeNode );
  50225. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  50226. const { dispatchSize } = computeNodeData;
  50227. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  50228. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  50229. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  50230. } else {
  50231. dispatchSize.x = computeNode.dispatchCount;
  50232. }
  50233. passEncoderGPU.dispatchWorkgroups(
  50234. dispatchSize.x,
  50235. dispatchSize.y,
  50236. dispatchSize.z
  50237. );
  50238. }
  50239. /**
  50240. * This method is executed at the end of a compute call and
  50241. * finalizes work after compute tasks.
  50242. *
  50243. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50244. */
  50245. finishCompute( computeGroup ) {
  50246. const groupData = this.get( computeGroup );
  50247. groupData.passEncoderGPU.end();
  50248. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  50249. }
  50250. /**
  50251. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  50252. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  50253. *
  50254. * @async
  50255. * @return {Promise} A Promise that resolves when synchronization has been finished.
  50256. */
  50257. async waitForGPU() {
  50258. await this.device.queue.onSubmittedWorkDone();
  50259. }
  50260. // render object
  50261. /**
  50262. * Executes a draw command for the given render object.
  50263. *
  50264. * @param {RenderObject} renderObject - The render object to draw.
  50265. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  50266. */
  50267. draw( renderObject, info ) {
  50268. const { object, material, context, pipeline } = renderObject;
  50269. const bindings = renderObject.getBindings();
  50270. const renderContextData = this.get( context );
  50271. const pipelineGPU = this.get( pipeline ).pipeline;
  50272. const index = renderObject.getIndex();
  50273. const hasIndex = ( index !== null );
  50274. const drawParams = renderObject.getDrawParameters();
  50275. if ( drawParams === null ) return;
  50276. // pipeline
  50277. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  50278. // pipeline
  50279. passEncoderGPU.setPipeline( pipelineGPU );
  50280. currentSets.pipeline = pipelineGPU;
  50281. // bind groups
  50282. const currentBindingGroups = currentSets.bindingGroups;
  50283. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50284. const bindGroup = bindings[ i ];
  50285. const bindingsData = this.get( bindGroup );
  50286. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  50287. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  50288. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  50289. }
  50290. }
  50291. // attributes
  50292. // index
  50293. if ( hasIndex === true ) {
  50294. if ( currentSets.index !== index ) {
  50295. const buffer = this.get( index ).buffer;
  50296. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  50297. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  50298. currentSets.index = index;
  50299. }
  50300. }
  50301. // vertex buffers
  50302. const vertexBuffers = renderObject.getVertexBuffers();
  50303. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  50304. const vertexBuffer = vertexBuffers[ i ];
  50305. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  50306. const buffer = this.get( vertexBuffer ).buffer;
  50307. passEncoderGPU.setVertexBuffer( i, buffer );
  50308. currentSets.attributes[ i ] = vertexBuffer;
  50309. }
  50310. }
  50311. // stencil
  50312. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  50313. passEncoderGPU.setStencilReference( material.stencilRef );
  50314. renderContextData.currentStencilRef = material.stencilRef;
  50315. }
  50316. };
  50317. // Define draw function
  50318. const draw = ( passEncoderGPU, currentSets ) => {
  50319. setPipelineAndBindings( passEncoderGPU, currentSets );
  50320. if ( object.isBatchedMesh === true ) {
  50321. const starts = object._multiDrawStarts;
  50322. const counts = object._multiDrawCounts;
  50323. const drawCount = object._multiDrawCount;
  50324. const drawInstances = object._multiDrawInstances;
  50325. if ( drawInstances !== null ) {
  50326. // @deprecated, r174
  50327. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  50328. }
  50329. for ( let i = 0; i < drawCount; i ++ ) {
  50330. const count = drawInstances ? drawInstances[ i ] : 1;
  50331. const firstInstance = count > 1 ? 0 : i;
  50332. if ( hasIndex === true ) {
  50333. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  50334. } else {
  50335. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  50336. }
  50337. info.update( object, counts[ i ], count );
  50338. }
  50339. } else if ( hasIndex === true ) {
  50340. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  50341. const indirect = renderObject.getIndirect();
  50342. if ( indirect !== null ) {
  50343. const buffer = this.get( indirect ).buffer;
  50344. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  50345. } else {
  50346. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  50347. }
  50348. info.update( object, indexCount, instanceCount );
  50349. } else {
  50350. const { vertexCount, instanceCount, firstVertex } = drawParams;
  50351. const indirect = renderObject.getIndirect();
  50352. if ( indirect !== null ) {
  50353. const buffer = this.get( indirect ).buffer;
  50354. passEncoderGPU.drawIndirect( buffer, 0 );
  50355. } else {
  50356. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  50357. }
  50358. info.update( object, vertexCount, instanceCount );
  50359. }
  50360. };
  50361. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  50362. const cameraData = this.get( renderObject.camera );
  50363. const cameras = renderObject.camera.cameras;
  50364. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  50365. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  50366. const bindingsData = this.get( cameraIndex );
  50367. const indexesGPU = [];
  50368. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  50369. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50370. data[ 0 ] = i;
  50371. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  50372. indexesGPU.push( bindGroupIndex );
  50373. }
  50374. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  50375. }
  50376. const pixelRatio = this.renderer.getPixelRatio();
  50377. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50378. const subCamera = cameras[ i ];
  50379. if ( object.layers.test( subCamera.layers ) ) {
  50380. const vp = subCamera.viewport;
  50381. let pass = renderContextData.currentPass;
  50382. let sets = renderContextData.currentSets;
  50383. if ( renderContextData.bundleEncoders ) {
  50384. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50385. const bundleSets = renderContextData.bundleSets[ i ];
  50386. pass = bundleEncoder;
  50387. sets = bundleSets;
  50388. }
  50389. if ( vp ) {
  50390. pass.setViewport(
  50391. Math.floor( vp.x * pixelRatio ),
  50392. Math.floor( vp.y * pixelRatio ),
  50393. Math.floor( vp.width * pixelRatio ),
  50394. Math.floor( vp.height * pixelRatio ),
  50395. context.viewportValue.minDepth,
  50396. context.viewportValue.maxDepth
  50397. );
  50398. }
  50399. // Set camera index binding for this layer
  50400. if ( cameraIndex && cameraData.indexesGPU ) {
  50401. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  50402. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  50403. }
  50404. draw( pass, sets );
  50405. }
  50406. }
  50407. } else {
  50408. // Regular single camera rendering
  50409. if ( renderContextData.currentPass ) {
  50410. // Handle occlusion queries
  50411. if ( renderContextData.occlusionQuerySet !== undefined ) {
  50412. const lastObject = renderContextData.lastOcclusionObject;
  50413. if ( lastObject !== object ) {
  50414. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  50415. renderContextData.currentPass.endOcclusionQuery();
  50416. renderContextData.occlusionQueryIndex ++;
  50417. }
  50418. if ( object.occlusionTest === true ) {
  50419. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  50420. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  50421. }
  50422. renderContextData.lastOcclusionObject = object;
  50423. }
  50424. }
  50425. draw( renderContextData.currentPass, renderContextData.currentSets );
  50426. }
  50427. }
  50428. }
  50429. // cache key
  50430. /**
  50431. * Returns `true` if the render pipeline requires an update.
  50432. *
  50433. * @param {RenderObject} renderObject - The render object.
  50434. * @return {boolean} Whether the render pipeline requires an update or not.
  50435. */
  50436. needsRenderUpdate( renderObject ) {
  50437. const data = this.get( renderObject );
  50438. const { object, material } = renderObject;
  50439. const utils = this.utils;
  50440. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  50441. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  50442. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  50443. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  50444. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  50445. let needsUpdate = false;
  50446. if ( data.material !== material || data.materialVersion !== material.version ||
  50447. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  50448. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  50449. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  50450. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  50451. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  50452. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  50453. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  50454. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  50455. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  50456. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  50457. data.primitiveTopology !== primitiveTopology ||
  50458. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  50459. ) {
  50460. data.material = material; data.materialVersion = material.version;
  50461. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  50462. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  50463. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  50464. data.colorWrite = material.colorWrite;
  50465. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  50466. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  50467. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  50468. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  50469. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  50470. data.sampleCount = sampleCount;
  50471. data.colorSpace = colorSpace;
  50472. data.colorFormat = colorFormat;
  50473. data.depthStencilFormat = depthStencilFormat;
  50474. data.primitiveTopology = primitiveTopology;
  50475. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  50476. needsUpdate = true;
  50477. }
  50478. return needsUpdate;
  50479. }
  50480. /**
  50481. * Returns a cache key that is used to identify render pipelines.
  50482. *
  50483. * @param {RenderObject} renderObject - The render object.
  50484. * @return {string} The cache key.
  50485. */
  50486. getRenderCacheKey( renderObject ) {
  50487. const { object, material } = renderObject;
  50488. const utils = this.utils;
  50489. const renderContext = renderObject.context;
  50490. return [
  50491. material.transparent, material.blending, material.premultipliedAlpha,
  50492. material.blendSrc, material.blendDst, material.blendEquation,
  50493. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  50494. material.colorWrite,
  50495. material.depthWrite, material.depthTest, material.depthFunc,
  50496. material.stencilWrite, material.stencilFunc,
  50497. material.stencilFail, material.stencilZFail, material.stencilZPass,
  50498. material.stencilFuncMask, material.stencilWriteMask,
  50499. material.side,
  50500. utils.getSampleCountRenderContext( renderContext ),
  50501. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  50502. utils.getPrimitiveTopology( object, material ),
  50503. renderObject.getGeometryCacheKey(),
  50504. renderObject.clippingContextCacheKey
  50505. ].join();
  50506. }
  50507. // textures
  50508. /**
  50509. * Creates a GPU sampler for the given texture.
  50510. *
  50511. * @param {Texture} texture - The texture to create the sampler for.
  50512. */
  50513. createSampler( texture ) {
  50514. this.textureUtils.createSampler( texture );
  50515. }
  50516. /**
  50517. * Destroys the GPU sampler for the given texture.
  50518. *
  50519. * @param {Texture} texture - The texture to destroy the sampler for.
  50520. */
  50521. destroySampler( texture ) {
  50522. this.textureUtils.destroySampler( texture );
  50523. }
  50524. /**
  50525. * Creates a default texture for the given texture that can be used
  50526. * as a placeholder until the actual texture is ready for usage.
  50527. *
  50528. * @param {Texture} texture - The texture to create a default texture for.
  50529. */
  50530. createDefaultTexture( texture ) {
  50531. this.textureUtils.createDefaultTexture( texture );
  50532. }
  50533. /**
  50534. * Defines a texture on the GPU for the given texture object.
  50535. *
  50536. * @param {Texture} texture - The texture.
  50537. * @param {Object} [options={}] - Optional configuration parameter.
  50538. */
  50539. createTexture( texture, options ) {
  50540. this.textureUtils.createTexture( texture, options );
  50541. }
  50542. /**
  50543. * Uploads the updated texture data to the GPU.
  50544. *
  50545. * @param {Texture} texture - The texture.
  50546. * @param {Object} [options={}] - Optional configuration parameter.
  50547. */
  50548. updateTexture( texture, options ) {
  50549. this.textureUtils.updateTexture( texture, options );
  50550. }
  50551. /**
  50552. * Generates mipmaps for the given texture.
  50553. *
  50554. * @param {Texture} texture - The texture.
  50555. */
  50556. generateMipmaps( texture ) {
  50557. this.textureUtils.generateMipmaps( texture );
  50558. }
  50559. /**
  50560. * Destroys the GPU data for the given texture object.
  50561. *
  50562. * @param {Texture} texture - The texture.
  50563. */
  50564. destroyTexture( texture ) {
  50565. this.textureUtils.destroyTexture( texture );
  50566. }
  50567. /**
  50568. * Returns texture data as a typed array.
  50569. *
  50570. * @async
  50571. * @param {Texture} texture - The texture to copy.
  50572. * @param {number} x - The x coordinate of the copy origin.
  50573. * @param {number} y - The y coordinate of the copy origin.
  50574. * @param {number} width - The width of the copy.
  50575. * @param {number} height - The height of the copy.
  50576. * @param {number} faceIndex - The face index.
  50577. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  50578. */
  50579. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  50580. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  50581. }
  50582. /**
  50583. * Inits a time stamp query for the given render context.
  50584. *
  50585. * @param {RenderContext} renderContext - The render context.
  50586. * @param {Object} descriptor - The query descriptor.
  50587. */
  50588. initTimestampQuery( renderContext, descriptor ) {
  50589. if ( ! this.trackTimestamp ) return;
  50590. const type = renderContext.isComputeNode ? 'compute' : 'render';
  50591. if ( ! this.timestampQueryPool[ type ] ) {
  50592. // TODO: Variable maxQueries?
  50593. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  50594. }
  50595. const timestampQueryPool = this.timestampQueryPool[ type ];
  50596. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  50597. descriptor.timestampWrites = {
  50598. querySet: timestampQueryPool.querySet,
  50599. beginningOfPassWriteIndex: baseOffset,
  50600. endOfPassWriteIndex: baseOffset + 1,
  50601. };
  50602. }
  50603. // node builder
  50604. /**
  50605. * Returns a node builder for the given render object.
  50606. *
  50607. * @param {RenderObject} object - The render object.
  50608. * @param {Renderer} renderer - The renderer.
  50609. * @return {WGSLNodeBuilder} The node builder.
  50610. */
  50611. createNodeBuilder( object, renderer ) {
  50612. return new WGSLNodeBuilder( object, renderer );
  50613. }
  50614. // program
  50615. /**
  50616. * Creates a shader program from the given programmable stage.
  50617. *
  50618. * @param {ProgrammableStage} program - The programmable stage.
  50619. */
  50620. createProgram( program ) {
  50621. const programGPU = this.get( program );
  50622. programGPU.module = {
  50623. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  50624. entryPoint: 'main'
  50625. };
  50626. }
  50627. /**
  50628. * Destroys the shader program of the given programmable stage.
  50629. *
  50630. * @param {ProgrammableStage} program - The programmable stage.
  50631. */
  50632. destroyProgram( program ) {
  50633. this.delete( program );
  50634. }
  50635. // pipelines
  50636. /**
  50637. * Creates a render pipeline for the given render object.
  50638. *
  50639. * @param {RenderObject} renderObject - The render object.
  50640. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  50641. */
  50642. createRenderPipeline( renderObject, promises ) {
  50643. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  50644. }
  50645. /**
  50646. * Creates a compute pipeline for the given compute node.
  50647. *
  50648. * @param {ComputePipeline} computePipeline - The compute pipeline.
  50649. * @param {Array<BindGroup>} bindings - The bindings.
  50650. */
  50651. createComputePipeline( computePipeline, bindings ) {
  50652. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  50653. }
  50654. /**
  50655. * Prepares the state for encoding render bundles.
  50656. *
  50657. * @param {RenderContext} renderContext - The render context.
  50658. */
  50659. beginBundle( renderContext ) {
  50660. const renderContextData = this.get( renderContext );
  50661. renderContextData._currentPass = renderContextData.currentPass;
  50662. renderContextData._currentSets = renderContextData.currentSets;
  50663. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  50664. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  50665. }
  50666. /**
  50667. * After processing render bundles this method finalizes related work.
  50668. *
  50669. * @param {RenderContext} renderContext - The render context.
  50670. * @param {RenderBundle} bundle - The render bundle.
  50671. */
  50672. finishBundle( renderContext, bundle ) {
  50673. const renderContextData = this.get( renderContext );
  50674. const bundleEncoder = renderContextData.currentPass;
  50675. const bundleGPU = bundleEncoder.finish();
  50676. this.get( bundle ).bundleGPU = bundleGPU;
  50677. // restore render pass state
  50678. renderContextData.currentSets = renderContextData._currentSets;
  50679. renderContextData.currentPass = renderContextData._currentPass;
  50680. }
  50681. /**
  50682. * Adds a render bundle to the render context data.
  50683. *
  50684. * @param {RenderContext} renderContext - The render context.
  50685. * @param {RenderBundle} bundle - The render bundle to add.
  50686. */
  50687. addBundle( renderContext, bundle ) {
  50688. const renderContextData = this.get( renderContext );
  50689. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  50690. }
  50691. // bindings
  50692. /**
  50693. * Creates bindings from the given bind group definition.
  50694. *
  50695. * @param {BindGroup} bindGroup - The bind group.
  50696. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50697. * @param {number} cacheIndex - The cache index.
  50698. * @param {number} version - The version.
  50699. */
  50700. createBindings( bindGroup, bindings, cacheIndex, version ) {
  50701. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  50702. }
  50703. /**
  50704. * Updates the given bind group definition.
  50705. *
  50706. * @param {BindGroup} bindGroup - The bind group.
  50707. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50708. * @param {number} cacheIndex - The cache index.
  50709. * @param {number} version - The version.
  50710. */
  50711. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  50712. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  50713. }
  50714. /**
  50715. * Updates a buffer binding.
  50716. *
  50717. * @param {Buffer} binding - The buffer binding to update.
  50718. */
  50719. updateBinding( binding ) {
  50720. this.bindingUtils.updateBinding( binding );
  50721. }
  50722. // attributes
  50723. /**
  50724. * Creates the buffer of an indexed shader attribute.
  50725. *
  50726. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  50727. */
  50728. createIndexAttribute( attribute ) {
  50729. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  50730. }
  50731. /**
  50732. * Creates the GPU buffer of a shader attribute.
  50733. *
  50734. * @param {BufferAttribute} attribute - The buffer attribute.
  50735. */
  50736. createAttribute( attribute ) {
  50737. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  50738. }
  50739. /**
  50740. * Creates the GPU buffer of a storage attribute.
  50741. *
  50742. * @param {BufferAttribute} attribute - The buffer attribute.
  50743. */
  50744. createStorageAttribute( attribute ) {
  50745. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  50746. }
  50747. /**
  50748. * Creates the GPU buffer of an indirect storage attribute.
  50749. *
  50750. * @param {BufferAttribute} attribute - The buffer attribute.
  50751. */
  50752. createIndirectStorageAttribute( attribute ) {
  50753. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  50754. }
  50755. /**
  50756. * Updates the GPU buffer of a shader attribute.
  50757. *
  50758. * @param {BufferAttribute} attribute - The buffer attribute to update.
  50759. */
  50760. updateAttribute( attribute ) {
  50761. this.attributeUtils.updateAttribute( attribute );
  50762. }
  50763. /**
  50764. * Destroys the GPU buffer of a shader attribute.
  50765. *
  50766. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  50767. */
  50768. destroyAttribute( attribute ) {
  50769. this.attributeUtils.destroyAttribute( attribute );
  50770. }
  50771. // canvas
  50772. /**
  50773. * Triggers an update of the default render pass descriptor.
  50774. */
  50775. updateSize() {
  50776. this.colorBuffer = this.textureUtils.getColorBuffer();
  50777. this.defaultRenderPassdescriptor = null;
  50778. }
  50779. // utils public
  50780. /**
  50781. * Returns the maximum anisotropy texture filtering value.
  50782. *
  50783. * @return {number} The maximum anisotropy texture filtering value.
  50784. */
  50785. getMaxAnisotropy() {
  50786. return 16;
  50787. }
  50788. /**
  50789. * Checks if the given feature is supported by the backend.
  50790. *
  50791. * @param {string} name - The feature's name.
  50792. * @return {boolean} Whether the feature is supported or not.
  50793. */
  50794. hasFeature( name ) {
  50795. return this.device.features.has( name );
  50796. }
  50797. /**
  50798. * Copies data of the given source texture to the given destination texture.
  50799. *
  50800. * @param {Texture} srcTexture - The source texture.
  50801. * @param {Texture} dstTexture - The destination texture.
  50802. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  50803. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  50804. * @param {number} [srcLevel=0] - The mipmap level to copy.
  50805. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  50806. */
  50807. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  50808. let dstX = 0;
  50809. let dstY = 0;
  50810. let dstZ = 0;
  50811. let srcX = 0;
  50812. let srcY = 0;
  50813. let srcZ = 0;
  50814. let srcWidth = srcTexture.image.width;
  50815. let srcHeight = srcTexture.image.height;
  50816. let srcDepth = 1;
  50817. if ( srcRegion !== null ) {
  50818. if ( srcRegion.isBox3 === true ) {
  50819. srcX = srcRegion.min.x;
  50820. srcY = srcRegion.min.y;
  50821. srcZ = srcRegion.min.z;
  50822. srcWidth = srcRegion.max.x - srcRegion.min.x;
  50823. srcHeight = srcRegion.max.y - srcRegion.min.y;
  50824. srcDepth = srcRegion.max.z - srcRegion.min.z;
  50825. } else {
  50826. // Assume it's a Box2
  50827. srcX = srcRegion.min.x;
  50828. srcY = srcRegion.min.y;
  50829. srcWidth = srcRegion.max.x - srcRegion.min.x;
  50830. srcHeight = srcRegion.max.y - srcRegion.min.y;
  50831. srcDepth = 1;
  50832. }
  50833. }
  50834. if ( dstPosition !== null ) {
  50835. dstX = dstPosition.x;
  50836. dstY = dstPosition.y;
  50837. dstZ = dstPosition.z || 0;
  50838. }
  50839. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  50840. const sourceGPU = this.get( srcTexture ).texture;
  50841. const destinationGPU = this.get( dstTexture ).texture;
  50842. encoder.copyTextureToTexture(
  50843. {
  50844. texture: sourceGPU,
  50845. mipLevel: srcLevel,
  50846. origin: { x: srcX, y: srcY, z: srcZ }
  50847. },
  50848. {
  50849. texture: destinationGPU,
  50850. mipLevel: dstLevel,
  50851. origin: { x: dstX, y: dstY, z: dstZ }
  50852. },
  50853. [
  50854. srcWidth,
  50855. srcHeight,
  50856. srcDepth
  50857. ]
  50858. );
  50859. this.device.queue.submit( [ encoder.finish() ] );
  50860. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  50861. this.textureUtils.generateMipmaps( dstTexture );
  50862. }
  50863. }
  50864. /**
  50865. * Copies the current bound framebuffer to the given texture.
  50866. *
  50867. * @param {Texture} texture - The destination texture.
  50868. * @param {RenderContext} renderContext - The render context.
  50869. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  50870. */
  50871. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  50872. const renderContextData = this.get( renderContext );
  50873. let sourceGPU = null;
  50874. if ( renderContext.renderTarget ) {
  50875. if ( texture.isDepthTexture ) {
  50876. sourceGPU = this.get( renderContext.depthTexture ).texture;
  50877. } else {
  50878. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  50879. }
  50880. } else {
  50881. if ( texture.isDepthTexture ) {
  50882. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  50883. } else {
  50884. sourceGPU = this.context.getCurrentTexture();
  50885. }
  50886. }
  50887. const destinationGPU = this.get( texture ).texture;
  50888. if ( sourceGPU.format !== destinationGPU.format ) {
  50889. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  50890. return;
  50891. }
  50892. let encoder;
  50893. if ( renderContextData.currentPass ) {
  50894. renderContextData.currentPass.end();
  50895. encoder = renderContextData.encoder;
  50896. } else {
  50897. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  50898. }
  50899. encoder.copyTextureToTexture(
  50900. {
  50901. texture: sourceGPU,
  50902. origin: [ rectangle.x, rectangle.y, 0 ],
  50903. },
  50904. {
  50905. texture: destinationGPU
  50906. },
  50907. [
  50908. rectangle.z,
  50909. rectangle.w
  50910. ]
  50911. );
  50912. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  50913. if ( renderContextData.currentPass ) {
  50914. const { descriptor } = renderContextData;
  50915. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  50916. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  50917. }
  50918. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50919. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50920. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  50921. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  50922. if ( renderContext.viewport ) {
  50923. this.updateViewport( renderContext );
  50924. }
  50925. if ( renderContext.scissor ) {
  50926. const { x, y, width, height } = renderContext.scissorValue;
  50927. renderContextData.currentPass.setScissorRect( x, y, width, height );
  50928. }
  50929. } else {
  50930. this.device.queue.submit( [ encoder.finish() ] );
  50931. }
  50932. }
  50933. }
  50934. /**
  50935. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  50936. *
  50937. * @augments SpotLight
  50938. */
  50939. class IESSpotLight extends SpotLight {
  50940. /**
  50941. * Constructs a new IES spot light.
  50942. *
  50943. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  50944. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  50945. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  50946. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  50947. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  50948. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  50949. */
  50950. constructor( color, intensity, distance, angle, penumbra, decay ) {
  50951. super( color, intensity, distance, angle, penumbra, decay );
  50952. /**
  50953. * TODO
  50954. *
  50955. * @type {?Texture}
  50956. * @default null
  50957. */
  50958. this.iesMap = null;
  50959. }
  50960. copy( source, recursive ) {
  50961. super.copy( source, recursive );
  50962. this.iesMap = source.iesMap;
  50963. return this;
  50964. }
  50965. }
  50966. /**
  50967. * This version of a node library represents the standard version
  50968. * used in {@link WebGPURenderer}. It maps lights, tone mapping
  50969. * techniques and materials to node-based implementations.
  50970. *
  50971. * @private
  50972. * @augments NodeLibrary
  50973. */
  50974. class StandardNodeLibrary extends NodeLibrary {
  50975. /**
  50976. * Constructs a new standard node library.
  50977. */
  50978. constructor() {
  50979. super();
  50980. this.addMaterial( MeshPhongNodeMaterial, 'MeshPhongMaterial' );
  50981. this.addMaterial( MeshStandardNodeMaterial, 'MeshStandardMaterial' );
  50982. this.addMaterial( MeshPhysicalNodeMaterial, 'MeshPhysicalMaterial' );
  50983. this.addMaterial( MeshToonNodeMaterial, 'MeshToonMaterial' );
  50984. this.addMaterial( MeshBasicNodeMaterial, 'MeshBasicMaterial' );
  50985. this.addMaterial( MeshLambertNodeMaterial, 'MeshLambertMaterial' );
  50986. this.addMaterial( MeshNormalNodeMaterial, 'MeshNormalMaterial' );
  50987. this.addMaterial( MeshMatcapNodeMaterial, 'MeshMatcapMaterial' );
  50988. this.addMaterial( LineBasicNodeMaterial, 'LineBasicMaterial' );
  50989. this.addMaterial( LineDashedNodeMaterial, 'LineDashedMaterial' );
  50990. this.addMaterial( PointsNodeMaterial, 'PointsMaterial' );
  50991. this.addMaterial( SpriteNodeMaterial, 'SpriteMaterial' );
  50992. this.addMaterial( ShadowNodeMaterial, 'ShadowMaterial' );
  50993. this.addLight( PointLightNode, PointLight );
  50994. this.addLight( DirectionalLightNode, DirectionalLight );
  50995. this.addLight( RectAreaLightNode, RectAreaLight );
  50996. this.addLight( SpotLightNode, SpotLight );
  50997. this.addLight( AmbientLightNode, AmbientLight );
  50998. this.addLight( HemisphereLightNode, HemisphereLight );
  50999. this.addLight( LightProbeNode, LightProbe );
  51000. this.addLight( IESSpotLightNode, IESSpotLight );
  51001. this.addToneMapping( linearToneMapping, LinearToneMapping );
  51002. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  51003. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  51004. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  51005. this.addToneMapping( agxToneMapping, AgXToneMapping );
  51006. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  51007. }
  51008. }
  51009. /*
  51010. const debugHandler = {
  51011. get: function ( target, name ) {
  51012. // Add |update
  51013. if ( /^(create|destroy)/.test( name ) ) console.log( 'WebGPUBackend.' + name );
  51014. return target[ name ];
  51015. }
  51016. };
  51017. */
  51018. /**
  51019. * This renderer is the new alternative of `WebGLRenderer`. `WebGPURenderer` has the ability
  51020. * to target different backends. By default, the renderer tries to use a WebGPU backend if the
  51021. * browser supports WebGPU. If not, `WebGPURenderer` falls backs to a WebGL 2 backend.
  51022. *
  51023. * @augments Renderer
  51024. */
  51025. class WebGPURenderer extends Renderer {
  51026. /**
  51027. * WebGPURenderer options.
  51028. *
  51029. * @typedef {Object} WebGPURenderer~Options
  51030. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  51031. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  51032. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  51033. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  51034. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  51035. * @property {number} [samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  51036. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  51037. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  51038. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  51039. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  51040. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  51041. */
  51042. /**
  51043. * Constructs a new WebGPU renderer.
  51044. *
  51045. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  51046. */
  51047. constructor( parameters = {} ) {
  51048. let BackendClass;
  51049. if ( parameters.forceWebGL ) {
  51050. BackendClass = WebGLBackend;
  51051. } else {
  51052. BackendClass = WebGPUBackend;
  51053. parameters.getFallback = () => {
  51054. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  51055. return new WebGLBackend( parameters );
  51056. };
  51057. }
  51058. const backend = new BackendClass( parameters );
  51059. //super( new Proxy( backend, debugHandler ) );
  51060. super( backend, parameters );
  51061. /**
  51062. * The generic default value is overwritten with the
  51063. * standard node library for type mapping.
  51064. *
  51065. * @type {StandardNodeLibrary}
  51066. */
  51067. this.library = new StandardNodeLibrary();
  51068. /**
  51069. * This flag can be used for type testing.
  51070. *
  51071. * @type {boolean}
  51072. * @readonly
  51073. * @default true
  51074. */
  51075. this.isWebGPURenderer = true;
  51076. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  51077. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  51078. }
  51079. }
  51080. }
  51081. /**
  51082. * A specialized group which enables applications access to the
  51083. * Render Bundle API of WebGPU. The group with all its descendant nodes
  51084. * are considered as one render bundle and processed as such by
  51085. * the renderer.
  51086. *
  51087. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  51088. * With a WebGL backend, the group can technically be rendered but without
  51089. * any performance improvements.
  51090. *
  51091. * @augments Group
  51092. */
  51093. class BundleGroup extends Group {
  51094. /**
  51095. * Constructs a new bundle group.
  51096. */
  51097. constructor() {
  51098. super();
  51099. /**
  51100. * This flag can be used for type testing.
  51101. *
  51102. * @type {boolean}
  51103. * @readonly
  51104. * @default true
  51105. */
  51106. this.isBundleGroup = true;
  51107. /**
  51108. * This property is only relevant for detecting types
  51109. * during serialization/deserialization. It should always
  51110. * match the class name.
  51111. *
  51112. * @type {string}
  51113. * @readonly
  51114. * @default 'BundleGroup'
  51115. */
  51116. this.type = 'BundleGroup';
  51117. /**
  51118. * Whether the bundle is static or not. When set to `true`, the structure
  51119. * is assumed to be static and does not change. E.g. no new objects are
  51120. * added to the group
  51121. *
  51122. * If a change is required, an update can still be forced by setting the
  51123. * `needsUpdate` flag to `true`.
  51124. *
  51125. * @type {boolean}
  51126. * @default true
  51127. */
  51128. this.static = true;
  51129. /**
  51130. * The bundle group's version.
  51131. *
  51132. * @type {number}
  51133. * @readonly
  51134. * @default 0
  51135. */
  51136. this.version = 0;
  51137. }
  51138. /**
  51139. * Set this property to `true` when the bundle group has changed.
  51140. *
  51141. * @type {boolean}
  51142. * @default false
  51143. * @param {boolean} value
  51144. */
  51145. set needsUpdate( value ) {
  51146. if ( value === true ) this.version ++;
  51147. }
  51148. }
  51149. /**
  51150. * This module is responsible to manage the post processing setups in apps.
  51151. * You usually create a single instance of this class and use it to define
  51152. * the output of your post processing effect chain.
  51153. * ```js
  51154. * const postProcessing = new PostProcessing( renderer );
  51155. *
  51156. * const scenePass = pass( scene, camera );
  51157. *
  51158. * postProcessing.outputNode = scenePass;
  51159. * ```
  51160. *
  51161. * Note: This module can only be used with `WebGPURenderer`.
  51162. */
  51163. class PostProcessing {
  51164. /**
  51165. * Constructs a new post processing management module.
  51166. *
  51167. * @param {Renderer} renderer - A reference to the renderer.
  51168. * @param {Node<vec4>} outputNode - An optional output node.
  51169. */
  51170. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  51171. /**
  51172. * A reference to the renderer.
  51173. *
  51174. * @type {Renderer}
  51175. */
  51176. this.renderer = renderer;
  51177. /**
  51178. * A node which defines the final output of the post
  51179. * processing. This is usually the last node in a chain
  51180. * of effect nodes.
  51181. *
  51182. * @type {Node<vec4>}
  51183. */
  51184. this.outputNode = outputNode;
  51185. /**
  51186. * Whether the default output tone mapping and color
  51187. * space transformation should be enabled or not.
  51188. *
  51189. * It is enabled by default by it must be disabled when
  51190. * effects must be executed after tone mapping and color
  51191. * space conversion. A typical example is FXAA which
  51192. * requires sRGB input.
  51193. *
  51194. * When set to `false`, the app must control the output
  51195. * transformation with `RenderOutputNode`.
  51196. *
  51197. * ```js
  51198. * const outputPass = renderOutput( scenePass );
  51199. * ```
  51200. *
  51201. * @type {boolean}
  51202. */
  51203. this.outputColorTransform = true;
  51204. /**
  51205. * Must be set to `true` when the output node changes.
  51206. *
  51207. * @type {Node<vec4>}
  51208. */
  51209. this.needsUpdate = true;
  51210. const material = new NodeMaterial();
  51211. material.name = 'PostProcessing';
  51212. /**
  51213. * The full screen quad that is used to render
  51214. * the effects.
  51215. *
  51216. * @private
  51217. * @type {QuadMesh}
  51218. */
  51219. this._quadMesh = new QuadMesh( material );
  51220. }
  51221. /**
  51222. * When `PostProcessing` is used to apply post processing effects,
  51223. * the application must use this version of `render()` inside
  51224. * its animation loop (not the one from the renderer).
  51225. */
  51226. render() {
  51227. this._update();
  51228. const renderer = this.renderer;
  51229. const toneMapping = renderer.toneMapping;
  51230. const outputColorSpace = renderer.outputColorSpace;
  51231. renderer.toneMapping = NoToneMapping;
  51232. renderer.outputColorSpace = LinearSRGBColorSpace;
  51233. //
  51234. const currentXR = renderer.xr.enabled;
  51235. renderer.xr.enabled = false;
  51236. this._quadMesh.render( renderer );
  51237. renderer.xr.enabled = currentXR;
  51238. //
  51239. renderer.toneMapping = toneMapping;
  51240. renderer.outputColorSpace = outputColorSpace;
  51241. }
  51242. /**
  51243. * Frees internal resources.
  51244. */
  51245. dispose() {
  51246. this._quadMesh.material.dispose();
  51247. }
  51248. /**
  51249. * Updates the state of the module.
  51250. *
  51251. * @private
  51252. */
  51253. _update() {
  51254. if ( this.needsUpdate === true ) {
  51255. const renderer = this.renderer;
  51256. const toneMapping = renderer.toneMapping;
  51257. const outputColorSpace = renderer.outputColorSpace;
  51258. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  51259. this._quadMesh.material.needsUpdate = true;
  51260. this.needsUpdate = false;
  51261. }
  51262. }
  51263. /**
  51264. * When `PostProcessing` is used to apply post processing effects,
  51265. * the application must use this version of `renderAsync()` inside
  51266. * its animation loop (not the one from the renderer).
  51267. *
  51268. * @async
  51269. * @return {Promise} A Promise that resolves when the render has been finished.
  51270. */
  51271. async renderAsync() {
  51272. this._update();
  51273. const renderer = this.renderer;
  51274. const toneMapping = renderer.toneMapping;
  51275. const outputColorSpace = renderer.outputColorSpace;
  51276. renderer.toneMapping = NoToneMapping;
  51277. renderer.outputColorSpace = LinearSRGBColorSpace;
  51278. //
  51279. const currentXR = renderer.xr.enabled;
  51280. renderer.xr.enabled = false;
  51281. await this._quadMesh.renderAsync( renderer );
  51282. renderer.xr.enabled = currentXR;
  51283. //
  51284. renderer.toneMapping = toneMapping;
  51285. renderer.outputColorSpace = outputColorSpace;
  51286. }
  51287. }
  51288. /**
  51289. * This special type of texture is intended for compute shaders.
  51290. * It can be used to compute the data of a texture with a compute shader.
  51291. *
  51292. * Note: This type of texture can only be used with `WebGPURenderer`
  51293. * and a WebGPU backend.
  51294. *
  51295. * @augments Texture
  51296. */
  51297. class StorageTexture extends Texture {
  51298. /**
  51299. * Constructs a new storage texture.
  51300. *
  51301. * @param {number} [width=1] - The storage texture's width.
  51302. * @param {number} [height=1] - The storage texture's height.
  51303. */
  51304. constructor( width = 1, height = 1 ) {
  51305. super();
  51306. /**
  51307. * The image object which just represents the texture's dimension.
  51308. *
  51309. * @type {{width: number, height: number}}
  51310. */
  51311. this.image = { width, height };
  51312. /**
  51313. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  51314. *
  51315. * @type {number}
  51316. */
  51317. this.magFilter = LinearFilter;
  51318. /**
  51319. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  51320. *
  51321. * @type {number}
  51322. */
  51323. this.minFilter = LinearFilter;
  51324. /**
  51325. * This flag can be used for type testing.
  51326. *
  51327. * @type {boolean}
  51328. * @readonly
  51329. * @default true
  51330. */
  51331. this.isStorageTexture = true;
  51332. }
  51333. }
  51334. /**
  51335. * This special type of buffer attribute is intended for compute shaders.
  51336. * It can be used to encode draw parameters for indirect draw calls.
  51337. *
  51338. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  51339. * and a WebGPU backend.
  51340. *
  51341. * @augments StorageBufferAttribute
  51342. */
  51343. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  51344. /**
  51345. * Constructs a new storage buffer attribute.
  51346. *
  51347. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  51348. * The subsequent parameter is then obsolete.
  51349. * @param {number} itemSize - The item size.
  51350. */
  51351. constructor( count, itemSize ) {
  51352. super( count, itemSize, Uint32Array );
  51353. /**
  51354. * This flag can be used for type testing.
  51355. *
  51356. * @type {boolean}
  51357. * @readonly
  51358. * @default true
  51359. */
  51360. this.isIndirectStorageBufferAttribute = true;
  51361. }
  51362. }
  51363. /**
  51364. * A loader for loading node objects in the three.js JSON Object/Scene format.
  51365. *
  51366. * @augments Loader
  51367. */
  51368. class NodeLoader extends Loader {
  51369. /**
  51370. * Constructs a new node loader.
  51371. *
  51372. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51373. */
  51374. constructor( manager ) {
  51375. super( manager );
  51376. /**
  51377. * Represents a dictionary of textures.
  51378. *
  51379. * @type {Object<string,Texture>}
  51380. */
  51381. this.textures = {};
  51382. /**
  51383. * Represents a dictionary of node types.
  51384. *
  51385. * @type {Object<string,Node.constructor>}
  51386. */
  51387. this.nodes = {};
  51388. }
  51389. /**
  51390. * Loads the node definitions from the given URL.
  51391. *
  51392. * @param {string} url - The path/URL of the file to be loaded.
  51393. * @param {Function} onLoad - Will be called when load completes.
  51394. * @param {Function} onProgress - Will be called while load progresses.
  51395. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  51396. */
  51397. load( url, onLoad, onProgress, onError ) {
  51398. const loader = new FileLoader( this.manager );
  51399. loader.setPath( this.path );
  51400. loader.setRequestHeader( this.requestHeader );
  51401. loader.setWithCredentials( this.withCredentials );
  51402. loader.load( url, ( text ) => {
  51403. try {
  51404. onLoad( this.parse( JSON.parse( text ) ) );
  51405. } catch ( e ) {
  51406. if ( onError ) {
  51407. onError( e );
  51408. } else {
  51409. console.error( e );
  51410. }
  51411. this.manager.itemError( url );
  51412. }
  51413. }, onProgress, onError );
  51414. }
  51415. /**
  51416. * Parse the node dependencies for the loaded node.
  51417. *
  51418. * @param {Array<Object>} [json] - The JSON definition
  51419. * @return {Object<string,Node>} A dictionary with node dependencies.
  51420. */
  51421. parseNodes( json ) {
  51422. const nodes = {};
  51423. if ( json !== undefined ) {
  51424. for ( const nodeJSON of json ) {
  51425. const { uuid, type } = nodeJSON;
  51426. nodes[ uuid ] = this.createNodeFromType( type );
  51427. nodes[ uuid ].uuid = uuid;
  51428. }
  51429. const meta = { nodes, textures: this.textures };
  51430. for ( const nodeJSON of json ) {
  51431. nodeJSON.meta = meta;
  51432. const node = nodes[ nodeJSON.uuid ];
  51433. node.deserialize( nodeJSON );
  51434. delete nodeJSON.meta;
  51435. }
  51436. }
  51437. return nodes;
  51438. }
  51439. /**
  51440. * Parses the node from the given JSON.
  51441. *
  51442. * @param {Object} json - The JSON definition
  51443. * @param {string} json.type - The node type.
  51444. * @param {string} json.uuid - The node UUID.
  51445. * @param {Array<Object>} [json.nodes] - The node dependencies.
  51446. * @param {Object} [json.meta] - The meta data.
  51447. * @return {Node} The parsed node.
  51448. */
  51449. parse( json ) {
  51450. const node = this.createNodeFromType( json.type );
  51451. node.uuid = json.uuid;
  51452. const nodes = this.parseNodes( json.nodes );
  51453. const meta = { nodes, textures: this.textures };
  51454. json.meta = meta;
  51455. node.deserialize( json );
  51456. delete json.meta;
  51457. return node;
  51458. }
  51459. /**
  51460. * Defines the dictionary of textures.
  51461. *
  51462. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  51463. * @return {NodeLoader} A reference to this loader.
  51464. */
  51465. setTextures( value ) {
  51466. this.textures = value;
  51467. return this;
  51468. }
  51469. /**
  51470. * Defines the dictionary of node types.
  51471. *
  51472. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  51473. * @return {NodeLoader} A reference to this loader.
  51474. */
  51475. setNodes( value ) {
  51476. this.nodes = value;
  51477. return this;
  51478. }
  51479. /**
  51480. * Creates a node object from the given type.
  51481. *
  51482. * @param {string} type - The node type.
  51483. * @return {Node} The created node instance.
  51484. */
  51485. createNodeFromType( type ) {
  51486. if ( this.nodes[ type ] === undefined ) {
  51487. console.error( 'THREE.NodeLoader: Node type not found:', type );
  51488. return float();
  51489. }
  51490. return nodeObject( new this.nodes[ type ]() );
  51491. }
  51492. }
  51493. /**
  51494. * A special type of material loader for loading node materials.
  51495. *
  51496. * @augments MaterialLoader
  51497. */
  51498. class NodeMaterialLoader extends MaterialLoader {
  51499. /**
  51500. * Constructs a new node material loader.
  51501. *
  51502. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51503. */
  51504. constructor( manager ) {
  51505. super( manager );
  51506. /**
  51507. * Represents a dictionary of node types.
  51508. *
  51509. * @type {Object<string,Node.constructor>}
  51510. */
  51511. this.nodes = {};
  51512. /**
  51513. * Represents a dictionary of node material types.
  51514. *
  51515. * @type {Object<string,NodeMaterial.constructor>}
  51516. */
  51517. this.nodeMaterials = {};
  51518. }
  51519. /**
  51520. * Parses the node material from the given JSON.
  51521. *
  51522. * @param {Object} json - The JSON definition
  51523. * @return {NodeMaterial}. The parsed material.
  51524. */
  51525. parse( json ) {
  51526. const material = super.parse( json );
  51527. const nodes = this.nodes;
  51528. const inputNodes = json.inputNodes;
  51529. for ( const property in inputNodes ) {
  51530. const uuid = inputNodes[ property ];
  51531. material[ property ] = nodes[ uuid ];
  51532. }
  51533. return material;
  51534. }
  51535. /**
  51536. * Defines the dictionary of node types.
  51537. *
  51538. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  51539. * @return {NodeLoader} A reference to this loader.
  51540. */
  51541. setNodes( value ) {
  51542. this.nodes = value;
  51543. return this;
  51544. }
  51545. /**
  51546. * Defines the dictionary of node material types.
  51547. *
  51548. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  51549. * @return {NodeLoader} A reference to this loader.
  51550. */
  51551. setNodeMaterials( value ) {
  51552. this.nodeMaterials = value;
  51553. return this;
  51554. }
  51555. /**
  51556. * Creates a node material from the given type.
  51557. *
  51558. * @param {string} type - The node material type.
  51559. * @return {Node} The created node material instance.
  51560. */
  51561. createMaterialFromType( type ) {
  51562. const materialClass = this.nodeMaterials[ type ];
  51563. if ( materialClass !== undefined ) {
  51564. return new materialClass();
  51565. }
  51566. return super.createMaterialFromType( type );
  51567. }
  51568. }
  51569. /**
  51570. * A special type of object loader for loading 3D objects using
  51571. * node materials.
  51572. *
  51573. * @augments ObjectLoader
  51574. */
  51575. class NodeObjectLoader extends ObjectLoader {
  51576. /**
  51577. * Constructs a new node object loader.
  51578. *
  51579. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51580. */
  51581. constructor( manager ) {
  51582. super( manager );
  51583. /**
  51584. * Represents a dictionary of node types.
  51585. *
  51586. * @type {Object<string,Node.constructor>}
  51587. */
  51588. this.nodes = {};
  51589. /**
  51590. * Represents a dictionary of node material types.
  51591. *
  51592. * @type {Object<string,NodeMaterial.constructor>}
  51593. */
  51594. this.nodeMaterials = {};
  51595. /**
  51596. * A reference to hold the `nodes` JSON property.
  51597. *
  51598. * @private
  51599. * @type {?Object[]}
  51600. */
  51601. this._nodesJSON = null;
  51602. }
  51603. /**
  51604. * Defines the dictionary of node types.
  51605. *
  51606. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  51607. * @return {NodeObjectLoader} A reference to this loader.
  51608. */
  51609. setNodes( value ) {
  51610. this.nodes = value;
  51611. return this;
  51612. }
  51613. /**
  51614. * Defines the dictionary of node material types.
  51615. *
  51616. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  51617. * @return {NodeObjectLoader} A reference to this loader.
  51618. */
  51619. setNodeMaterials( value ) {
  51620. this.nodeMaterials = value;
  51621. return this;
  51622. }
  51623. /**
  51624. * Parses the node objects from the given JSON.
  51625. *
  51626. * @param {Object} json - The JSON definition
  51627. * @param {Function} onLoad - The onLoad callback function.
  51628. * @return {Object3D}. The parsed 3D object.
  51629. */
  51630. parse( json, onLoad ) {
  51631. this._nodesJSON = json.nodes;
  51632. const data = super.parse( json, onLoad );
  51633. this._nodesJSON = null; // dispose
  51634. return data;
  51635. }
  51636. /**
  51637. * Parses the node objects from the given JSON and textures.
  51638. *
  51639. * @param {Object[]} json - The JSON definition
  51640. * @param {Object<string,Texture>} textures - The texture library.
  51641. * @return {Object<string,Node>}. The parsed nodes.
  51642. */
  51643. parseNodes( json, textures ) {
  51644. if ( json !== undefined ) {
  51645. const loader = new NodeLoader();
  51646. loader.setNodes( this.nodes );
  51647. loader.setTextures( textures );
  51648. return loader.parseNodes( json );
  51649. }
  51650. return {};
  51651. }
  51652. /**
  51653. * Parses the node objects from the given JSON and textures.
  51654. *
  51655. * @param {Object} json - The JSON definition
  51656. * @param {Object<string,Texture>} textures - The texture library.
  51657. * @return {Object<string,NodeMaterial>}. The parsed materials.
  51658. */
  51659. parseMaterials( json, textures ) {
  51660. const materials = {};
  51661. if ( json !== undefined ) {
  51662. const nodes = this.parseNodes( this._nodesJSON, textures );
  51663. const loader = new NodeMaterialLoader();
  51664. loader.setTextures( textures );
  51665. loader.setNodes( nodes );
  51666. loader.setNodeMaterials( this.nodeMaterials );
  51667. for ( let i = 0, l = json.length; i < l; i ++ ) {
  51668. const data = json[ i ];
  51669. materials[ data.uuid ] = loader.parse( data );
  51670. }
  51671. }
  51672. return materials;
  51673. }
  51674. }
  51675. /**
  51676. * In earlier three.js versions, clipping was defined globally
  51677. * on the renderer or on material level. This special version of
  51678. * `THREE.Group` allows to encode the clipping state into the scene
  51679. * graph. Meaning if you create an instance of this group, all
  51680. * descendant 3D objects will be affected by the respective clipping
  51681. * planes.
  51682. *
  51683. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  51684. *
  51685. * @augments Group
  51686. */
  51687. class ClippingGroup extends Group {
  51688. /**
  51689. * Constructs a new clipping group.
  51690. */
  51691. constructor() {
  51692. super();
  51693. /**
  51694. * This flag can be used for type testing.
  51695. *
  51696. * @type {boolean}
  51697. * @readonly
  51698. * @default true
  51699. */
  51700. this.isClippingGroup = true;
  51701. /**
  51702. * An array with clipping planes.
  51703. *
  51704. * @type {Array<Plane>}
  51705. */
  51706. this.clippingPlanes = [];
  51707. /**
  51708. * Whether clipping should be enabled or not.
  51709. *
  51710. * @type {boolean}
  51711. * @default true
  51712. */
  51713. this.enabled = true;
  51714. /**
  51715. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  51716. *
  51717. * @type {boolean}
  51718. * @default false
  51719. */
  51720. this.clipIntersection = false;
  51721. /**
  51722. * Whether shadows should be clipped or not.
  51723. *
  51724. * @type {boolean}
  51725. * @default false
  51726. */
  51727. this.clipShadows = false;
  51728. }
  51729. }
  51730. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthArrayTexture, 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, FrustumArray, 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, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RenderTargetArray, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };