three.webgpu.nodes.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. import { Color, Vector2, Vector3, Vector4, Matrix3, Matrix4, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, DynamicDrawUsage, InterleavedBufferAttribute, NoColorSpace, UnsignedIntType, IntType, BackSide, CubeReflectionMapping, CubeRefractionMapping, TangentSpaceNormalMap, ObjectSpaceNormalMap, InstancedInterleavedBuffer, InstancedBufferAttribute, DataArrayTexture, FloatType, FramebufferTexture, LinearMipmapLinearFilter, DepthTexture, Material, NormalBlending, LineBasicMaterial, LineDashedMaterial, NoBlending, MeshNormalMaterial, WebGLCubeRenderTarget, BoxGeometry, Mesh, Scene, LinearFilter, CubeCamera, CubeTexture, EquirectangularReflectionMapping, EquirectangularRefractionMapping, AddOperation, MixOperation, MultiplyOperation, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, Texture, MeshStandardMaterial, MeshPhysicalMaterial, MeshToonMaterial, MeshMatcapMaterial, SpriteMaterial, PointsMaterial, ShadowMaterial, Uint32BufferAttribute, Uint16BufferAttribute, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, RenderTarget, Plane, Object3D, HalfFloatType, LinearMipMapLinearFilter, OrthographicCamera, BufferGeometry, Float32BufferAttribute, BufferAttribute, UVMapping, Euler, LinearSRGBColorSpace, LessCompare, VSMShadowMap, RGFormat, BasicShadowMap, SphereGeometry, CubeUVReflectionMapping, PerspectiveCamera, RGBAFormat, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, WebXRController, RAD2DEG, SRGBColorSpace, PCFShadowMap, FrontSide, Frustum, DataTexture, RedIntegerFormat, RedFormat, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, UnsignedShortType, ByteType, ShortType, createCanvasElement, AddEquation, SubtractEquation, ReverseSubtractEquation, ZeroFactor, OneFactor, SrcColorFactor, SrcAlphaFactor, SrcAlphaSaturateFactor, DstColorFactor, DstAlphaFactor, OneMinusSrcColorFactor, OneMinusSrcAlphaFactor, OneMinusDstColorFactor, OneMinusDstAlphaFactor, CullFaceNone, CullFaceBack, CullFaceFront, CustomBlending, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, LuminanceFormat, LuminanceAlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, RepeatWrapping, ClampToEdgeWrapping, MirroredRepeatWrapping, NearestFilter, NearestMipmapNearestFilter, NeverCompare, AlwaysCompare, LessEqualCompare, EqualCompare, GreaterEqualCompare, GreaterCompare, NotEqualCompare, warnOnce, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, CylinderGeometry, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LinearTransfer, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, Matrix2, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneGeometry, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, Quaternion, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RenderTargetArray, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Sphere, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'attenuationColor',
  16. 'attenuationDistance',
  17. 'bumpMap',
  18. 'clearcoat',
  19. 'clearcoatMap',
  20. 'clearcoatNormalMap',
  21. 'clearcoatNormalScale',
  22. 'clearcoatRoughness',
  23. 'color',
  24. 'dispersion',
  25. 'displacementMap',
  26. 'emissive',
  27. 'emissiveMap',
  28. 'envMap',
  29. 'gradientMap',
  30. 'ior',
  31. 'iridescence',
  32. 'iridescenceIOR',
  33. 'iridescenceMap',
  34. 'iridescenceThicknessMap',
  35. 'lightMap',
  36. 'map',
  37. 'matcap',
  38. 'metalness',
  39. 'metalnessMap',
  40. 'normalMap',
  41. 'normalScale',
  42. 'opacity',
  43. 'roughness',
  44. 'roughnessMap',
  45. 'sheen',
  46. 'sheenColor',
  47. 'sheenColorMap',
  48. 'sheenRoughnessMap',
  49. 'shininess',
  50. 'specular',
  51. 'specularColor',
  52. 'specularColorMap',
  53. 'specularIntensity',
  54. 'specularIntensityMap',
  55. 'specularMap',
  56. 'thickness',
  57. 'transmission',
  58. 'transmissionMap'
  59. ];
  60. /**
  61. * This class is used by {@link WebGPURenderer} as management component.
  62. * It's primary purpose is to determine whether render objects require a
  63. * refresh right before they are going to be rendered or not.
  64. */
  65. class NodeMaterialObserver {
  66. /**
  67. * Constructs a new node material observer.
  68. *
  69. * @param {NodeBuilder} builder - The node builder.
  70. */
  71. constructor( builder ) {
  72. /**
  73. * A node material can be used by more than one render object so the
  74. * monitor must maintain a list of render objects.
  75. *
  76. * @type {WeakMap<RenderObject,Object>}
  77. */
  78. this.renderObjects = new WeakMap();
  79. /**
  80. * Whether the material uses node objects or not.
  81. *
  82. * @type {Boolean}
  83. */
  84. this.hasNode = this.containsNode( builder );
  85. /**
  86. * Whether the node builder's 3D object is animated or not.
  87. *
  88. * @type {Boolean}
  89. */
  90. this.hasAnimation = builder.object.isSkinnedMesh === true;
  91. /**
  92. * A list of all possible material uniforms
  93. *
  94. * @type {Array<String>}
  95. */
  96. this.refreshUniforms = refreshUniforms;
  97. /**
  98. * Holds the current render ID from the node frame.
  99. *
  100. * @type {Number}
  101. * @default 0
  102. */
  103. this.renderId = 0;
  104. }
  105. /**
  106. * Returns `true` if the given render object is verified for the first time of this observer.
  107. *
  108. * @param {RenderObject} renderObject - The render object.
  109. * @return {Boolean} Whether the given render object is verified for the first time of this observer.
  110. */
  111. firstInitialization( renderObject ) {
  112. const hasInitialized = this.renderObjects.has( renderObject );
  113. if ( hasInitialized === false ) {
  114. this.getRenderObjectData( renderObject );
  115. return true;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Returns monitoring data for the given render object.
  121. *
  122. * @param {RenderObject} renderObject - The render object.
  123. * @return {Object} The monitoring data.
  124. */
  125. getRenderObjectData( renderObject ) {
  126. let data = this.renderObjects.get( renderObject );
  127. if ( data === undefined ) {
  128. const { geometry, material, object } = renderObject;
  129. data = {
  130. material: this.getMaterialData( material ),
  131. geometry: {
  132. attributes: this.getAttributesData( geometry.attributes ),
  133. indexVersion: geometry.index ? geometry.index.version : null,
  134. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  135. },
  136. worldMatrix: object.matrixWorld.clone()
  137. };
  138. if ( object.center ) {
  139. data.center = object.center.clone();
  140. }
  141. if ( object.morphTargetInfluences ) {
  142. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  143. }
  144. if ( renderObject.bundle !== null ) {
  145. data.version = renderObject.bundle.version;
  146. }
  147. if ( data.material.transmission > 0 ) {
  148. const { width, height } = renderObject.context;
  149. data.bufferWidth = width;
  150. data.bufferHeight = height;
  151. }
  152. this.renderObjects.set( renderObject, data );
  153. }
  154. return data;
  155. }
  156. /**
  157. * Returns an attribute data structure holding the attributes versions for
  158. * monitoring.
  159. *
  160. * @param {Object} attributes - The geometry attributes.
  161. * @return {Object} An object for monitoring the versions of attributes.
  162. */
  163. getAttributesData( attributes ) {
  164. const attributesData = {};
  165. for ( const name in attributes ) {
  166. const attribute = attributes[ name ];
  167. attributesData[ name ] = {
  168. version: attribute.version
  169. };
  170. }
  171. return attributesData;
  172. }
  173. /**
  174. * Returns `true` if the node builder's material uses
  175. * node properties.
  176. *
  177. * @param {NodeBuilder} builder - The current node builder.
  178. * @return {Boolean} Whether the node builder's material uses node properties or not.
  179. */
  180. containsNode( builder ) {
  181. const material = builder.material;
  182. for ( const property in material ) {
  183. if ( material[ property ] && material[ property ].isNode )
  184. return true;
  185. }
  186. if ( builder.renderer.nodes.modelViewMatrix !== null || builder.renderer.nodes.modelNormalViewMatrix !== null )
  187. return true;
  188. return false;
  189. }
  190. /**
  191. * Returns a material data structure holding the material property values for
  192. * monitoring.
  193. *
  194. * @param {Material} material - The material.
  195. * @return {Object} An object for monitoring material properties.
  196. */
  197. getMaterialData( material ) {
  198. const data = {};
  199. for ( const property of this.refreshUniforms ) {
  200. const value = material[ property ];
  201. if ( value === null || value === undefined ) continue;
  202. if ( typeof value === 'object' && value.clone !== undefined ) {
  203. if ( value.isTexture === true ) {
  204. data[ property ] = { id: value.id, version: value.version };
  205. } else {
  206. data[ property ] = value.clone();
  207. }
  208. } else {
  209. data[ property ] = value;
  210. }
  211. }
  212. return data;
  213. }
  214. /**
  215. * Returns `true` if the given render object has not changed its state.
  216. *
  217. * @param {RenderObject} renderObject - The render object.
  218. * @return {Boolean} Whether the given render object has changed its state or not.
  219. */
  220. equals( renderObject ) {
  221. const { object, material, geometry } = renderObject;
  222. const renderObjectData = this.getRenderObjectData( renderObject );
  223. // world matrix
  224. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  225. renderObjectData.worldMatrix.copy( object.matrixWorld );
  226. return false;
  227. }
  228. // material
  229. const materialData = renderObjectData.material;
  230. for ( const property in materialData ) {
  231. const value = materialData[ property ];
  232. const mtlValue = material[ property ];
  233. if ( value.equals !== undefined ) {
  234. if ( value.equals( mtlValue ) === false ) {
  235. value.copy( mtlValue );
  236. return false;
  237. }
  238. } else if ( mtlValue.isTexture === true ) {
  239. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  240. value.id = mtlValue.id;
  241. value.version = mtlValue.version;
  242. return false;
  243. }
  244. } else if ( value !== mtlValue ) {
  245. materialData[ property ] = mtlValue;
  246. return false;
  247. }
  248. }
  249. if ( materialData.transmission > 0 ) {
  250. const { width, height } = renderObject.context;
  251. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  252. renderObjectData.bufferWidth = width;
  253. renderObjectData.bufferHeight = height;
  254. return false;
  255. }
  256. }
  257. // geometry
  258. const storedGeometryData = renderObjectData.geometry;
  259. const attributes = geometry.attributes;
  260. const storedAttributes = storedGeometryData.attributes;
  261. const storedAttributeNames = Object.keys( storedAttributes );
  262. const currentAttributeNames = Object.keys( attributes );
  263. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  264. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  265. return false;
  266. }
  267. // compare each attribute
  268. for ( const name of storedAttributeNames ) {
  269. const storedAttributeData = storedAttributes[ name ];
  270. const attribute = attributes[ name ];
  271. if ( attribute === undefined ) {
  272. // attribute was removed
  273. delete storedAttributes[ name ];
  274. return false;
  275. }
  276. if ( storedAttributeData.version !== attribute.version ) {
  277. storedAttributeData.version = attribute.version;
  278. return false;
  279. }
  280. }
  281. // check index
  282. const index = geometry.index;
  283. const storedIndexVersion = storedGeometryData.indexVersion;
  284. const currentIndexVersion = index ? index.version : null;
  285. if ( storedIndexVersion !== currentIndexVersion ) {
  286. storedGeometryData.indexVersion = currentIndexVersion;
  287. return false;
  288. }
  289. // check drawRange
  290. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  291. storedGeometryData.drawRange.start = geometry.drawRange.start;
  292. storedGeometryData.drawRange.count = geometry.drawRange.count;
  293. return false;
  294. }
  295. // morph targets
  296. if ( renderObjectData.morphTargetInfluences ) {
  297. let morphChanged = false;
  298. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  299. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  300. morphChanged = true;
  301. }
  302. }
  303. if ( morphChanged ) return true;
  304. }
  305. // center
  306. if ( renderObjectData.center ) {
  307. if ( renderObjectData.center.equals( object.center ) === false ) {
  308. renderObjectData.center.copy( object.center );
  309. return true;
  310. }
  311. }
  312. // bundle
  313. if ( renderObject.bundle !== null ) {
  314. renderObjectData.version = renderObject.bundle.version;
  315. }
  316. return true;
  317. }
  318. /**
  319. * Checks if the given render object requires a refresh.
  320. *
  321. * @param {RenderObject} renderObject - The render object.
  322. * @param {NodeFrame} nodeFrame - The current node frame.
  323. * @return {Boolean} Whether the given render object requires a refresh or not.
  324. */
  325. needsRefresh( renderObject, nodeFrame ) {
  326. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) )
  327. return true;
  328. const { renderId } = nodeFrame;
  329. if ( this.renderId !== renderId ) {
  330. this.renderId = renderId;
  331. return true;
  332. }
  333. const isStatic = renderObject.object.static === true;
  334. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  335. if ( isStatic || isBundle )
  336. return false;
  337. const notEqual = this.equals( renderObject ) !== true;
  338. return notEqual;
  339. }
  340. }
  341. /** @module NodeUtils **/
  342. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  343. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  344. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  345. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  346. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  347. function cyrb53( value, seed = 0 ) {
  348. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  349. if ( value instanceof Array ) {
  350. for ( let i = 0, val; i < value.length; i ++ ) {
  351. val = value[ i ];
  352. h1 = Math.imul( h1 ^ val, 2654435761 );
  353. h2 = Math.imul( h2 ^ val, 1597334677 );
  354. }
  355. } else {
  356. for ( let i = 0, ch; i < value.length; i ++ ) {
  357. ch = value.charCodeAt( i );
  358. h1 = Math.imul( h1 ^ ch, 2654435761 );
  359. h2 = Math.imul( h2 ^ ch, 1597334677 );
  360. }
  361. }
  362. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  363. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  364. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  365. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  366. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  367. }
  368. /**
  369. * Computes a hash for the given string.
  370. *
  371. * @method
  372. * @param {String} str - The string to be hashed.
  373. * @return {Number} The hash.
  374. */
  375. const hashString = ( str ) => cyrb53( str );
  376. /**
  377. * Computes a hash for the given array.
  378. *
  379. * @method
  380. * @param {Array<Number>} array - The array to be hashed.
  381. * @return {Number} The hash.
  382. */
  383. const hashArray = ( array ) => cyrb53( array );
  384. /**
  385. * Computes a hash for the given list of parameters.
  386. *
  387. * @method
  388. * @param {...Number} params - A list of parameters.
  389. * @return {Number} The hash.
  390. */
  391. const hash$1 = ( ...params ) => cyrb53( params );
  392. /**
  393. * Computes a cache key for the given node.
  394. *
  395. * @method
  396. * @param {Object} object - The object to be hashed.
  397. * @param {Boolean} [force=false] - Whether to force a cache key computation or not.
  398. * @return {Number} The hash.
  399. */
  400. function getCacheKey$1( object, force = false ) {
  401. const values = [];
  402. if ( object.isNode === true ) {
  403. values.push( object.id );
  404. object = object.getSelf();
  405. }
  406. for ( const { property, childNode } of getNodeChildren( object ) ) {
  407. values.push( cyrb53( property.slice( 0, - 4 ) ), childNode.getCacheKey( force ) );
  408. }
  409. return cyrb53( values );
  410. }
  411. /**
  412. * This generator function can be used to iterate over the node children
  413. * of the given object.
  414. *
  415. * @generator
  416. * @param {Object} node - The object to be hashed.
  417. * @param {Boolean} [toJSON=false] - Whether to return JSON or not.
  418. * @yields {Object} A result node holding the property, index (if available) and the child node.
  419. */
  420. function* getNodeChildren( node, toJSON = false ) {
  421. for ( const property in node ) {
  422. // Ignore private properties.
  423. if ( property.startsWith( '_' ) === true ) continue;
  424. const object = node[ property ];
  425. if ( Array.isArray( object ) === true ) {
  426. for ( let i = 0; i < object.length; i ++ ) {
  427. const child = object[ i ];
  428. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  429. yield { property, index: i, childNode: child };
  430. }
  431. }
  432. } else if ( object && object.isNode === true ) {
  433. yield { property, childNode: object };
  434. } else if ( typeof object === 'object' ) {
  435. for ( const subProperty in object ) {
  436. const child = object[ subProperty ];
  437. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  438. yield { property, index: subProperty, childNode: child };
  439. }
  440. }
  441. }
  442. }
  443. }
  444. const typeFromLength = /*@__PURE__*/ new Map( [
  445. [ 1, 'float' ],
  446. [ 2, 'vec2' ],
  447. [ 3, 'vec3' ],
  448. [ 4, 'vec4' ],
  449. [ 9, 'mat3' ],
  450. [ 16, 'mat4' ]
  451. ] );
  452. const dataFromObject = /*@__PURE__*/ new WeakMap();
  453. /**
  454. * Returns the data type for the given the length.
  455. *
  456. * @method
  457. * @param {Number} length - The length.
  458. * @return {String} The data type.
  459. */
  460. function getTypeFromLength( length ) {
  461. return typeFromLength.get( length );
  462. }
  463. /**
  464. * Returns the typed array for the given data type.
  465. *
  466. * @method
  467. * @param {String} type - The data type.
  468. * @return {TypedArray} The typed array.
  469. */
  470. function getTypedArrayFromType( type ) {
  471. // Handle component type for vectors and matrices
  472. if ( /[iu]?vec\d/.test( type ) ) {
  473. // Handle int vectors
  474. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  475. // Handle uint vectors
  476. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  477. // Default to float vectors
  478. return Float32Array;
  479. }
  480. // Handle matrices (always float)
  481. if ( /mat\d/.test( type ) ) return Float32Array;
  482. // Basic types
  483. if ( /float/.test( type ) ) return Float32Array;
  484. if ( /uint/.test( type ) ) return Uint32Array;
  485. if ( /int/.test( type ) ) return Int32Array;
  486. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  487. }
  488. /**
  489. * Returns the length for the given data type.
  490. *
  491. * @method
  492. * @param {String} type - The data type.
  493. * @return {Number} The length.
  494. */
  495. function getLengthFromType( type ) {
  496. if ( /float|int|uint/.test( type ) ) return 1;
  497. if ( /vec2/.test( type ) ) return 2;
  498. if ( /vec3/.test( type ) ) return 3;
  499. if ( /vec4/.test( type ) ) return 4;
  500. if ( /mat3/.test( type ) ) return 9;
  501. if ( /mat4/.test( type ) ) return 16;
  502. console.error( 'THREE.TSL: Unsupported type:', type );
  503. }
  504. /**
  505. * Returns the data type for the given value.
  506. *
  507. * @method
  508. * @param {Any} value - The value.
  509. * @return {String?} The data type.
  510. */
  511. function getValueType( value ) {
  512. if ( value === undefined || value === null ) return null;
  513. const typeOf = typeof value;
  514. if ( value.isNode === true ) {
  515. return 'node';
  516. } else if ( typeOf === 'number' ) {
  517. return 'float';
  518. } else if ( typeOf === 'boolean' ) {
  519. return 'bool';
  520. } else if ( typeOf === 'string' ) {
  521. return 'string';
  522. } else if ( typeOf === 'function' ) {
  523. return 'shader';
  524. } else if ( value.isVector2 === true ) {
  525. return 'vec2';
  526. } else if ( value.isVector3 === true ) {
  527. return 'vec3';
  528. } else if ( value.isVector4 === true ) {
  529. return 'vec4';
  530. } else if ( value.isMatrix3 === true ) {
  531. return 'mat3';
  532. } else if ( value.isMatrix4 === true ) {
  533. return 'mat4';
  534. } else if ( value.isColor === true ) {
  535. return 'color';
  536. } else if ( value instanceof ArrayBuffer ) {
  537. return 'ArrayBuffer';
  538. }
  539. return null;
  540. }
  541. /**
  542. * Returns the value/object for the given data type and parameters.
  543. *
  544. * @method
  545. * @param {String} type - The given type.
  546. * @param {...Any} params - A parameter list.
  547. * @return {Any} The value/object.
  548. */
  549. function getValueFromType( type, ...params ) {
  550. const last4 = type ? type.slice( - 4 ) : undefined;
  551. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  552. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  553. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  554. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  555. }
  556. if ( type === 'color' ) {
  557. return new Color( ...params );
  558. } else if ( last4 === 'vec2' ) {
  559. return new Vector2( ...params );
  560. } else if ( last4 === 'vec3' ) {
  561. return new Vector3( ...params );
  562. } else if ( last4 === 'vec4' ) {
  563. return new Vector4( ...params );
  564. } else if ( last4 === 'mat3' ) {
  565. return new Matrix3( ...params );
  566. } else if ( last4 === 'mat4' ) {
  567. return new Matrix4( ...params );
  568. } else if ( type === 'bool' ) {
  569. return params[ 0 ] || false;
  570. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  571. return params[ 0 ] || 0;
  572. } else if ( type === 'string' ) {
  573. return params[ 0 ] || '';
  574. } else if ( type === 'ArrayBuffer' ) {
  575. return base64ToArrayBuffer( params[ 0 ] );
  576. }
  577. return null;
  578. }
  579. /**
  580. * Gets the object data that can be shared between different rendering steps.
  581. *
  582. * @param {Object} object - The object to get the data for.
  583. * @return {Object} The object data.
  584. */
  585. function getDataFromObject( object ) {
  586. let data = dataFromObject.get( object );
  587. if ( data === undefined ) {
  588. data = {};
  589. dataFromObject.set( object, data );
  590. }
  591. return data;
  592. }
  593. /**
  594. * Converts the given array buffer to a Base64 string.
  595. *
  596. * @method
  597. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  598. * @return {String} The Base64 string.
  599. */
  600. function arrayBufferToBase64( arrayBuffer ) {
  601. let chars = '';
  602. const array = new Uint8Array( arrayBuffer );
  603. for ( let i = 0; i < array.length; i ++ ) {
  604. chars += String.fromCharCode( array[ i ] );
  605. }
  606. return btoa( chars );
  607. }
  608. /**
  609. * Converts the given Base64 string to an array buffer.
  610. *
  611. * @method
  612. * @param {String} base64 - The Base64 string.
  613. * @return {ArrayBuffer} The array buffer.
  614. */
  615. function base64ToArrayBuffer( base64 ) {
  616. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  617. }
  618. var NodeUtils = /*#__PURE__*/Object.freeze({
  619. __proto__: null,
  620. arrayBufferToBase64: arrayBufferToBase64,
  621. base64ToArrayBuffer: base64ToArrayBuffer,
  622. getCacheKey: getCacheKey$1,
  623. getDataFromObject: getDataFromObject,
  624. getLengthFromType: getLengthFromType,
  625. getNodeChildren: getNodeChildren,
  626. getTypeFromLength: getTypeFromLength,
  627. getTypedArrayFromType: getTypedArrayFromType,
  628. getValueFromType: getValueFromType,
  629. getValueType: getValueType,
  630. hash: hash$1,
  631. hashArray: hashArray,
  632. hashString: hashString
  633. });
  634. /** @module NodeConstants **/
  635. /**
  636. * Possible shader stages.
  637. *
  638. * @property {string} VERTEX The vertex shader stage.
  639. * @property {string} FRAGMENT The fragment shader stage.
  640. */
  641. const NodeShaderStage = {
  642. VERTEX: 'vertex',
  643. FRAGMENT: 'fragment'
  644. };
  645. /**
  646. * Update types of a node.
  647. *
  648. * @property {string} NONE The update method is not executed.
  649. * @property {string} FRAME The update method is executed per frame.
  650. * @property {string} RENDER The update method is executed per render. A frame might be produced by multiple render calls so this value allows more detailed updates than FRAME.
  651. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  652. */
  653. const NodeUpdateType = {
  654. NONE: 'none',
  655. FRAME: 'frame',
  656. RENDER: 'render',
  657. OBJECT: 'object'
  658. };
  659. /**
  660. * Data types of a node.
  661. *
  662. * @property {string} BOOLEAN Boolean type.
  663. * @property {string} INTEGER Integer type.
  664. * @property {string} FLOAT Float type.
  665. * @property {string} VECTOR2 Two-dimensional vector type.
  666. * @property {string} VECTOR3 Three-dimensional vector type.
  667. * @property {string} VECTOR4 Four-dimensional vector type.
  668. * @property {string} MATRIX2 2x2 matrix type.
  669. * @property {string} MATRIX3 3x3 matrix type.
  670. * @property {string} MATRIX4 4x4 matrix type.
  671. */
  672. const NodeType = {
  673. BOOLEAN: 'bool',
  674. INTEGER: 'int',
  675. FLOAT: 'float',
  676. VECTOR2: 'vec2',
  677. VECTOR3: 'vec3',
  678. VECTOR4: 'vec4',
  679. MATRIX2: 'mat2',
  680. MATRIX3: 'mat3',
  681. MATRIX4: 'mat4'
  682. };
  683. /**
  684. * Access types of a node. These are relevant for compute and storage usage.
  685. *
  686. * @property {string} READ_ONLY Read-only access
  687. * @property {string} WRITE_ONLY Write-only access.
  688. * @property {string} READ_WRITE Read and write access.
  689. */
  690. const NodeAccess = {
  691. READ_ONLY: 'readOnly',
  692. WRITE_ONLY: 'writeOnly',
  693. READ_WRITE: 'readWrite',
  694. };
  695. const defaultShaderStages = [ 'fragment', 'vertex' ];
  696. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  697. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  698. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  699. let _nodeId = 0;
  700. /**
  701. * Base class for all nodes.
  702. *
  703. * @augments EventDispatcher
  704. */
  705. class Node extends EventDispatcher {
  706. static get type() {
  707. return 'Node';
  708. }
  709. /**
  710. * Constructs a new node.
  711. *
  712. * @param {String?} nodeType - The node type.
  713. */
  714. constructor( nodeType = null ) {
  715. super();
  716. /**
  717. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  718. *
  719. * @type {String?}
  720. * @default null
  721. */
  722. this.nodeType = nodeType;
  723. /**
  724. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  725. *
  726. * @type {String}
  727. * @default 'none'
  728. */
  729. this.updateType = NodeUpdateType.NONE;
  730. /**
  731. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  732. *
  733. * @type {String}
  734. * @default 'none'
  735. */
  736. this.updateBeforeType = NodeUpdateType.NONE;
  737. /**
  738. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  739. *
  740. * @type {String}
  741. * @default 'none'
  742. */
  743. this.updateAfterType = NodeUpdateType.NONE;
  744. /**
  745. * The UUID of the node.
  746. *
  747. * @type {String}
  748. * @readonly
  749. */
  750. this.uuid = MathUtils.generateUUID();
  751. /**
  752. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  753. *
  754. * @type {Number}
  755. * @readonly
  756. * @default 0
  757. */
  758. this.version = 0;
  759. /**
  760. * Whether this node is global or not. This property is relevant for the internal
  761. * node caching system. All nodes which should be declared just once should
  762. * set this flag to `true` (a typical example is {@link AttributeNode}).
  763. *
  764. * @type {Boolean}
  765. * @default false
  766. */
  767. this.global = false;
  768. /**
  769. * This flag can be used for type testing.
  770. *
  771. * @type {Boolean}
  772. * @readonly
  773. * @default true
  774. */
  775. this.isNode = true;
  776. // private
  777. /**
  778. * The cache key of this node.
  779. *
  780. * @private
  781. * @type {Number?}
  782. * @default null
  783. */
  784. this._cacheKey = null;
  785. /**
  786. * The cache key 's version.
  787. *
  788. * @private
  789. * @type {Number}
  790. * @default 0
  791. */
  792. this._cacheKeyVersion = 0;
  793. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  794. }
  795. /**
  796. * Set this property to `true` when the node should be regenerated.
  797. *
  798. * @type {Boolean}
  799. * @default false
  800. * @param {boolean} value
  801. */
  802. set needsUpdate( value ) {
  803. if ( value === true ) {
  804. this.version ++;
  805. }
  806. }
  807. /**
  808. * The type of the class. The value is usually the constructor name.
  809. *
  810. * @type {String}
  811. * @readonly
  812. */
  813. get type() {
  814. return this.constructor.type;
  815. }
  816. /**
  817. * Convenient method for defining {@link Node#update}.
  818. *
  819. * @param {Function} callback - The update method.
  820. * @param {String} updateType - The update type.
  821. * @return {Node} A reference to this node.
  822. */
  823. onUpdate( callback, updateType ) {
  824. this.updateType = updateType;
  825. this.update = callback.bind( this.getSelf() );
  826. return this;
  827. }
  828. /**
  829. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  830. * this method automatically sets the update type to `FRAME`.
  831. *
  832. * @param {Function} callback - The update method.
  833. * @return {Node} A reference to this node.
  834. */
  835. onFrameUpdate( callback ) {
  836. return this.onUpdate( callback, NodeUpdateType.FRAME );
  837. }
  838. /**
  839. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  840. * this method automatically sets the update type to `RENDER`.
  841. *
  842. * @param {Function} callback - The update method.
  843. * @return {Node} A reference to this node.
  844. */
  845. onRenderUpdate( callback ) {
  846. return this.onUpdate( callback, NodeUpdateType.RENDER );
  847. }
  848. /**
  849. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  850. * this method automatically sets the update type to `OBJECT`.
  851. *
  852. * @param {Function} callback - The update method.
  853. * @return {Node} A reference to this node.
  854. */
  855. onObjectUpdate( callback ) {
  856. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  857. }
  858. /**
  859. * Convenient method for defining {@link Node#updateReference}.
  860. *
  861. * @param {Function} callback - The update method.
  862. * @return {Node} A reference to this node.
  863. */
  864. onReference( callback ) {
  865. this.updateReference = callback.bind( this.getSelf() );
  866. return this;
  867. }
  868. /**
  869. * The `this` reference might point to a Proxy so this method can be used
  870. * to get the reference to the actual node instance.
  871. *
  872. * @return {Node} A reference to the node.
  873. */
  874. getSelf() {
  875. // Returns non-node object.
  876. return this.self || this;
  877. }
  878. /**
  879. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  880. * to such objects based on a given state (e.g. the current node frame or builder).
  881. *
  882. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  883. * @return {Any} The updated reference.
  884. */
  885. updateReference( /*state*/ ) {
  886. return this;
  887. }
  888. /**
  889. * By default this method returns the value of the {@link Node#global} flag. This method
  890. * can be overwritten in derived classes if an analytical way is required to determine the
  891. * global status.
  892. *
  893. * @param {NodeBuilder} builder - The current node builder.
  894. * @return {Boolean} Whether this node is global or not.
  895. */
  896. isGlobal( /*builder*/ ) {
  897. return this.global;
  898. }
  899. /**
  900. * Generator function that can be used to iterate over the child nodes.
  901. *
  902. * @generator
  903. * @yields {Node} A child node.
  904. */
  905. * getChildren() {
  906. for ( const { childNode } of getNodeChildren( this ) ) {
  907. yield childNode;
  908. }
  909. }
  910. /**
  911. * Calling this method dispatches the `dispose` event. This event can be used
  912. * to register event listeners for clean up tasks.
  913. */
  914. dispose() {
  915. this.dispatchEvent( { type: 'dispose' } );
  916. }
  917. /**
  918. * Callback for {@link Node#traverse}.
  919. *
  920. * @callback traverseCallback
  921. * @param {Node} node - The current node.
  922. */
  923. /**
  924. * Can be used to traverse through the node's hierarchy.
  925. *
  926. * @param {traverseCallback} callback - A callback that is executed per node.
  927. */
  928. traverse( callback ) {
  929. callback( this );
  930. for ( const childNode of this.getChildren() ) {
  931. childNode.traverse( callback );
  932. }
  933. }
  934. /**
  935. * Returns the cache key for this node.
  936. *
  937. * @param {Boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  938. * @return {Number} The cache key of the node.
  939. */
  940. getCacheKey( force = false ) {
  941. force = force || this.version !== this._cacheKeyVersion;
  942. if ( force === true || this._cacheKey === null ) {
  943. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  944. this._cacheKeyVersion = this.version;
  945. }
  946. return this._cacheKey;
  947. }
  948. /**
  949. * Generate a custom cache key for this node.
  950. *
  951. * @return {Number} The cache key of the node.
  952. */
  953. customCacheKey() {
  954. return 0;
  955. }
  956. /**
  957. * Returns the references to this node which is by default `this`.
  958. *
  959. * @return {Node} A reference to this node.
  960. */
  961. getScope() {
  962. return this;
  963. }
  964. /**
  965. * Returns the hash of the node which is used to identify the node. By default it's
  966. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  967. * depending on their implementation.
  968. *
  969. * @param {NodeBuilder} builder - The current node builder.
  970. * @return {String} The hash.
  971. */
  972. getHash( /*builder*/ ) {
  973. return this.uuid;
  974. }
  975. /**
  976. * Returns the update type of {@link Node#update}.
  977. *
  978. * @return {NodeUpdateType} The update type.
  979. */
  980. getUpdateType() {
  981. return this.updateType;
  982. }
  983. /**
  984. * Returns the update type of {@link Node#updateBefore}.
  985. *
  986. * @return {NodeUpdateType} The update type.
  987. */
  988. getUpdateBeforeType() {
  989. return this.updateBeforeType;
  990. }
  991. /**
  992. * Returns the update type of {@link Node#updateAfter}.
  993. *
  994. * @return {NodeUpdateType} The update type.
  995. */
  996. getUpdateAfterType() {
  997. return this.updateAfterType;
  998. }
  999. /**
  1000. * Certain types are composed of multiple elements. For example a `vec3`
  1001. * is composed of three `float` values. This method returns the type of
  1002. * these elements.
  1003. *
  1004. * @param {NodeBuilder} builder - The current node builder.
  1005. * @return {String} The type of the node.
  1006. */
  1007. getElementType( builder ) {
  1008. const type = this.getNodeType( builder );
  1009. const elementType = builder.getElementType( type );
  1010. return elementType;
  1011. }
  1012. /**
  1013. * Returns the node's type.
  1014. *
  1015. * @param {NodeBuilder} builder - The current node builder.
  1016. * @return {String} The type of the node.
  1017. */
  1018. getNodeType( builder ) {
  1019. const nodeProperties = builder.getNodeProperties( this );
  1020. if ( nodeProperties.outputNode ) {
  1021. return nodeProperties.outputNode.getNodeType( builder );
  1022. }
  1023. return this.nodeType;
  1024. }
  1025. /**
  1026. * This method is used during the build process of a node and ensures
  1027. * equal nodes are not built multiple times but just once. For example if
  1028. * `attribute( 'uv' )` is used multiple times by the user, the build
  1029. * process makes sure to process just the first node.
  1030. *
  1031. * @param {NodeBuilder} builder - The current node builder.
  1032. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1033. */
  1034. getShared( builder ) {
  1035. const hash = this.getHash( builder );
  1036. const nodeFromHash = builder.getNodeFromHash( hash );
  1037. return nodeFromHash || this;
  1038. }
  1039. /**
  1040. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1041. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1042. * The output node must be returned in the `return` statement.
  1043. *
  1044. * @param {NodeBuilder} builder - The current node builder.
  1045. * @return {Node?} The output node.
  1046. */
  1047. setup( builder ) {
  1048. const nodeProperties = builder.getNodeProperties( this );
  1049. let index = 0;
  1050. for ( const childNode of this.getChildren() ) {
  1051. nodeProperties[ 'node' + index ++ ] = childNode;
  1052. }
  1053. // return a outputNode if exists or null
  1054. return nodeProperties.outputNode || null;
  1055. }
  1056. /**
  1057. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1058. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1059. *
  1060. * @param {NodeBuilder} builder - The current node builder.
  1061. */
  1062. analyze( builder ) {
  1063. const usageCount = builder.increaseUsage( this );
  1064. if ( usageCount === 1 ) {
  1065. // node flow children
  1066. const nodeProperties = builder.getNodeProperties( this );
  1067. for ( const childNode of Object.values( nodeProperties ) ) {
  1068. if ( childNode && childNode.isNode === true ) {
  1069. childNode.build( builder );
  1070. }
  1071. }
  1072. }
  1073. }
  1074. /**
  1075. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1076. * This state builds the output node and returns the resulting shader string.
  1077. *
  1078. * @param {NodeBuilder} builder - The current node builder.
  1079. * @param {String?} output - Can be used to define the output type.
  1080. * @return {String?} The generated shader string.
  1081. */
  1082. generate( builder, output ) {
  1083. const { outputNode } = builder.getNodeProperties( this );
  1084. if ( outputNode && outputNode.isNode === true ) {
  1085. return outputNode.build( builder, output );
  1086. }
  1087. }
  1088. /**
  1089. * The method can be implemented to update the node's internal state before it is used to render an object.
  1090. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1091. *
  1092. * @abstract
  1093. * @param {NodeFrame} frame - A reference to the current node frame.
  1094. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1095. */
  1096. updateBefore( /*frame*/ ) {
  1097. console.warn( 'Abstract function.' );
  1098. }
  1099. /**
  1100. * The method can be implemented to update the node's internal state after it was used to render an object.
  1101. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1102. *
  1103. * @abstract
  1104. * @param {NodeFrame} frame - A reference to the current node frame.
  1105. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1106. */
  1107. updateAfter( /*frame*/ ) {
  1108. console.warn( 'Abstract function.' );
  1109. }
  1110. /**
  1111. * The method can be implemented to update the node's internal state when it is used to render an object.
  1112. * The {@link Node#updateType} property defines how often the update is executed.
  1113. *
  1114. * @abstract
  1115. * @param {NodeFrame} frame - A reference to the current node frame.
  1116. * @return {Boolean?} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1117. */
  1118. update( /*frame*/ ) {
  1119. console.warn( 'Abstract function.' );
  1120. }
  1121. /**
  1122. * This method performs the build of a node. The behavior of this method as well as its return value depend
  1123. * on the current build stage (setup, analyze or generate).
  1124. *
  1125. * @param {NodeBuilder} builder - The current node builder.
  1126. * @param {String?} output - Can be used to define the output type.
  1127. * @return {String?} When this method is executed in the setup or analyze stage, `null` is returned. In the generate stage, the generated shader string.
  1128. */
  1129. build( builder, output = null ) {
  1130. const refNode = this.getShared( builder );
  1131. if ( this !== refNode ) {
  1132. return refNode.build( builder, output );
  1133. }
  1134. builder.addNode( this );
  1135. builder.addChain( this );
  1136. /* Build stages expected results:
  1137. - "setup" -> Node
  1138. - "analyze" -> null
  1139. - "generate" -> String
  1140. */
  1141. let result = null;
  1142. const buildStage = builder.getBuildStage();
  1143. if ( buildStage === 'setup' ) {
  1144. this.updateReference( builder );
  1145. const properties = builder.getNodeProperties( this );
  1146. if ( properties.initialized !== true ) {
  1147. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1148. properties.initialized = true;
  1149. const outputNode = this.setup( builder ); // return a node or null
  1150. const isNodeOutput = outputNode && outputNode.isNode === true;
  1151. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1152. // !! no outputNode !!
  1153. //outputNode = builder.stack;
  1154. }*/
  1155. for ( const childNode of Object.values( properties ) ) {
  1156. if ( childNode && childNode.isNode === true ) {
  1157. childNode.build( builder );
  1158. }
  1159. }
  1160. if ( isNodeOutput ) {
  1161. outputNode.build( builder );
  1162. }
  1163. properties.outputNode = outputNode;
  1164. }
  1165. } else if ( buildStage === 'analyze' ) {
  1166. this.analyze( builder );
  1167. } else if ( buildStage === 'generate' ) {
  1168. const isGenerateOnce = this.generate.length === 1;
  1169. if ( isGenerateOnce ) {
  1170. const type = this.getNodeType( builder );
  1171. const nodeData = builder.getDataFromNode( this );
  1172. result = nodeData.snippet;
  1173. if ( result === undefined ) {
  1174. result = this.generate( builder ) || '';
  1175. nodeData.snippet = result;
  1176. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1177. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1178. }
  1179. result = builder.format( result, type, output );
  1180. } else {
  1181. result = this.generate( builder, output ) || '';
  1182. }
  1183. }
  1184. builder.removeChain( this );
  1185. builder.addSequentialNode( this );
  1186. return result;
  1187. }
  1188. /**
  1189. * Returns the child nodes as a JSON object.
  1190. *
  1191. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1192. */
  1193. getSerializeChildren() {
  1194. return getNodeChildren( this );
  1195. }
  1196. /**
  1197. * Serializes the node to JSON.
  1198. *
  1199. * @param {Object} json - The output JSON object.
  1200. */
  1201. serialize( json ) {
  1202. const nodeChildren = this.getSerializeChildren();
  1203. const inputNodes = {};
  1204. for ( const { property, index, childNode } of nodeChildren ) {
  1205. if ( index !== undefined ) {
  1206. if ( inputNodes[ property ] === undefined ) {
  1207. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1208. }
  1209. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1210. } else {
  1211. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1212. }
  1213. }
  1214. if ( Object.keys( inputNodes ).length > 0 ) {
  1215. json.inputNodes = inputNodes;
  1216. }
  1217. }
  1218. /**
  1219. * Deserializes the node from the given JSON.
  1220. *
  1221. * @param {Object} json - The JSON object.
  1222. */
  1223. deserialize( json ) {
  1224. if ( json.inputNodes !== undefined ) {
  1225. const nodes = json.meta.nodes;
  1226. for ( const property in json.inputNodes ) {
  1227. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1228. const inputArray = [];
  1229. for ( const uuid of json.inputNodes[ property ] ) {
  1230. inputArray.push( nodes[ uuid ] );
  1231. }
  1232. this[ property ] = inputArray;
  1233. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1234. const inputObject = {};
  1235. for ( const subProperty in json.inputNodes[ property ] ) {
  1236. const uuid = json.inputNodes[ property ][ subProperty ];
  1237. inputObject[ subProperty ] = nodes[ uuid ];
  1238. }
  1239. this[ property ] = inputObject;
  1240. } else {
  1241. const uuid = json.inputNodes[ property ];
  1242. this[ property ] = nodes[ uuid ];
  1243. }
  1244. }
  1245. }
  1246. }
  1247. /**
  1248. * Serializes the node into the three.js JSON Object/Scene format.
  1249. *
  1250. * @param {Object?} meta - An optional JSON object that already holds serialized data from other scene objects.
  1251. * @return {Object} The serialized node.
  1252. */
  1253. toJSON( meta ) {
  1254. const { uuid, type } = this;
  1255. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1256. if ( isRoot ) {
  1257. meta = {
  1258. textures: {},
  1259. images: {},
  1260. nodes: {}
  1261. };
  1262. }
  1263. // serialize
  1264. let data = meta.nodes[ uuid ];
  1265. if ( data === undefined ) {
  1266. data = {
  1267. uuid,
  1268. type,
  1269. meta,
  1270. metadata: {
  1271. version: 4.6,
  1272. type: 'Node',
  1273. generator: 'Node.toJSON'
  1274. }
  1275. };
  1276. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1277. this.serialize( data );
  1278. delete data.meta;
  1279. }
  1280. // TODO: Copied from Object3D.toJSON
  1281. function extractFromCache( cache ) {
  1282. const values = [];
  1283. for ( const key in cache ) {
  1284. const data = cache[ key ];
  1285. delete data.metadata;
  1286. values.push( data );
  1287. }
  1288. return values;
  1289. }
  1290. if ( isRoot ) {
  1291. const textures = extractFromCache( meta.textures );
  1292. const images = extractFromCache( meta.images );
  1293. const nodes = extractFromCache( meta.nodes );
  1294. if ( textures.length > 0 ) data.textures = textures;
  1295. if ( images.length > 0 ) data.images = images;
  1296. if ( nodes.length > 0 ) data.nodes = nodes;
  1297. }
  1298. return data;
  1299. }
  1300. }
  1301. /**
  1302. * Base class for representing element access on an array-like
  1303. * node data structures.
  1304. *
  1305. * @augments Node
  1306. */
  1307. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1308. static get type() {
  1309. return 'ArrayElementNode';
  1310. }
  1311. /**
  1312. * Constructs an array element node.
  1313. *
  1314. * @param {Node} node - The array-like node.
  1315. * @param {Node} indexNode - The index node that defines the element access.
  1316. */
  1317. constructor( node, indexNode ) {
  1318. super();
  1319. /**
  1320. * The array-like node.
  1321. *
  1322. * @type {Node}
  1323. */
  1324. this.node = node;
  1325. /**
  1326. * The index node that defines the element access.
  1327. *
  1328. * @type {Node}
  1329. */
  1330. this.indexNode = indexNode;
  1331. /**
  1332. * This flag can be used for type testing.
  1333. *
  1334. * @type {Boolean}
  1335. * @readonly
  1336. * @default true
  1337. */
  1338. this.isArrayElementNode = true;
  1339. }
  1340. /**
  1341. * This method is overwritten since the node type is inferred from the array-like node.
  1342. *
  1343. * @param {NodeBuilder} builder - The current node builder.
  1344. * @return {String} The node type.
  1345. */
  1346. getNodeType( builder ) {
  1347. return this.node.getElementType( builder );
  1348. }
  1349. generate( builder ) {
  1350. const nodeSnippet = this.node.build( builder );
  1351. const indexSnippet = this.indexNode.build( builder, 'uint' );
  1352. return `${nodeSnippet}[ ${indexSnippet} ]`;
  1353. }
  1354. }
  1355. /**
  1356. * This module is part of the TSL core and usually not used in app level code.
  1357. * It represents a convert operation during the shader generation process
  1358. * meaning it converts the data type of a node to a target data type.
  1359. *
  1360. * @augments Node
  1361. */
  1362. class ConvertNode extends Node {
  1363. static get type() {
  1364. return 'ConvertNode';
  1365. }
  1366. /**
  1367. * Constructs a new convert node.
  1368. *
  1369. * @param {Node} node - The node which type should be converted.
  1370. * @param {String} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1371. */
  1372. constructor( node, convertTo ) {
  1373. super();
  1374. /**
  1375. * The node which type should be converted.
  1376. *
  1377. * @type {Node}
  1378. */
  1379. this.node = node;
  1380. /**
  1381. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1382. *
  1383. * @type {String}
  1384. */
  1385. this.convertTo = convertTo;
  1386. }
  1387. /**
  1388. * This method is overwritten since the implementation tries to infer the best
  1389. * matching type from the {@link ConvertNode#convertTo} property.
  1390. *
  1391. * @param {NodeBuilder} builder - The current node builder.
  1392. * @return {String} The node type.
  1393. */
  1394. getNodeType( builder ) {
  1395. const requestType = this.node.getNodeType( builder );
  1396. let convertTo = null;
  1397. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1398. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1399. convertTo = overloadingType;
  1400. }
  1401. }
  1402. return convertTo;
  1403. }
  1404. serialize( data ) {
  1405. super.serialize( data );
  1406. data.convertTo = this.convertTo;
  1407. }
  1408. deserialize( data ) {
  1409. super.deserialize( data );
  1410. this.convertTo = data.convertTo;
  1411. }
  1412. generate( builder, output ) {
  1413. const node = this.node;
  1414. const type = this.getNodeType( builder );
  1415. const snippet = node.build( builder, type );
  1416. return builder.format( snippet, type, output );
  1417. }
  1418. }
  1419. /**
  1420. * This module uses cache management to create temporary variables
  1421. * if the node is used more than once to prevent duplicate calculations.
  1422. *
  1423. * The class acts as a base class for many other nodes types.
  1424. *
  1425. * @augments Node
  1426. */
  1427. class TempNode extends Node {
  1428. static get type() {
  1429. return 'TempNode';
  1430. }
  1431. /**
  1432. * Constructs a temp node.
  1433. *
  1434. * @param {String?} nodeType - The node type.
  1435. */
  1436. constructor( nodeType = null ) {
  1437. super( nodeType );
  1438. /**
  1439. * This flag can be used for type testing.
  1440. *
  1441. * @type {Boolean}
  1442. * @readonly
  1443. * @default true
  1444. */
  1445. this.isTempNode = true;
  1446. }
  1447. /**
  1448. * Whether this node is used more than once in context of other nodes.
  1449. *
  1450. * @param {NodeBuilder} builder - The node builder.
  1451. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes.
  1452. */
  1453. hasDependencies( builder ) {
  1454. return builder.getDataFromNode( this ).usageCount > 1;
  1455. }
  1456. build( builder, output ) {
  1457. const buildStage = builder.getBuildStage();
  1458. if ( buildStage === 'generate' ) {
  1459. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1460. const nodeData = builder.getDataFromNode( this );
  1461. if ( nodeData.propertyName !== undefined ) {
  1462. return builder.format( nodeData.propertyName, type, output );
  1463. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1464. const snippet = super.build( builder, type );
  1465. const nodeVar = builder.getVarFromNode( this, null, type );
  1466. const propertyName = builder.getPropertyName( nodeVar );
  1467. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  1468. nodeData.snippet = snippet;
  1469. nodeData.propertyName = propertyName;
  1470. return builder.format( nodeData.propertyName, type, output );
  1471. }
  1472. }
  1473. return super.build( builder, output );
  1474. }
  1475. }
  1476. /**
  1477. * This module is part of the TSL core and usually not used in app level code.
  1478. * It represents a join operation during the shader generation process.
  1479. * For example in can compose/join two single floats into a `vec2` type.
  1480. *
  1481. * @augments TempNode
  1482. */
  1483. class JoinNode extends TempNode {
  1484. static get type() {
  1485. return 'JoinNode';
  1486. }
  1487. /**
  1488. * Constructs a new join node.
  1489. *
  1490. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1491. * @param {String?} [nodeType=null] - The node type.
  1492. */
  1493. constructor( nodes = [], nodeType = null ) {
  1494. super( nodeType );
  1495. /**
  1496. * An array of nodes that should be joined.
  1497. *
  1498. * @type {Array<Node>}
  1499. */
  1500. this.nodes = nodes;
  1501. }
  1502. /**
  1503. * This method is overwritten since the node type must be inferred from the
  1504. * joined data length if not explicitly defined.
  1505. *
  1506. * @param {NodeBuilder} builder - The current node builder.
  1507. * @return {String} The node type.
  1508. */
  1509. getNodeType( builder ) {
  1510. if ( this.nodeType !== null ) {
  1511. return builder.getVectorType( this.nodeType );
  1512. }
  1513. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1514. }
  1515. generate( builder, output ) {
  1516. const type = this.getNodeType( builder );
  1517. const nodes = this.nodes;
  1518. const primitiveType = builder.getComponentType( type );
  1519. const snippetValues = [];
  1520. for ( const input of nodes ) {
  1521. let inputSnippet = input.build( builder );
  1522. const inputPrimitiveType = builder.getComponentType( input.getNodeType( builder ) );
  1523. if ( inputPrimitiveType !== primitiveType ) {
  1524. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1525. }
  1526. snippetValues.push( inputSnippet );
  1527. }
  1528. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1529. return builder.format( snippet, type, output );
  1530. }
  1531. }
  1532. const _stringVectorComponents = vectorComponents.join( '' );
  1533. /**
  1534. * This module is part of the TSL core and usually not used in app level code.
  1535. * `SplitNode` represents a property access operation which means it is
  1536. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1537. * For example:
  1538. * ```js
  1539. * const redValue = color.r;
  1540. * ```
  1541. *
  1542. * @augments Node
  1543. */
  1544. class SplitNode extends Node {
  1545. static get type() {
  1546. return 'SplitNode';
  1547. }
  1548. /**
  1549. * Constructs a new split node.
  1550. *
  1551. * @param {Node} node - The node that should be accessed.
  1552. * @param {String} [components='x'] - The components that should be accessed.
  1553. */
  1554. constructor( node, components = 'x' ) {
  1555. super();
  1556. /**
  1557. * The node that should be accessed.
  1558. *
  1559. * @type {Node}
  1560. */
  1561. this.node = node;
  1562. /**
  1563. * The components that should be accessed.
  1564. *
  1565. * @type {string}
  1566. */
  1567. this.components = components;
  1568. /**
  1569. * This flag can be used for type testing.
  1570. *
  1571. * @type {Boolean}
  1572. * @readonly
  1573. * @default true
  1574. */
  1575. this.isSplitNode = true;
  1576. }
  1577. /**
  1578. * Returns the vector length which is computed based on the requested components.
  1579. *
  1580. * @return {Number} The vector length.
  1581. */
  1582. getVectorLength() {
  1583. let vectorLength = this.components.length;
  1584. for ( const c of this.components ) {
  1585. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1586. }
  1587. return vectorLength;
  1588. }
  1589. /**
  1590. * Returns the component type of the node's type.
  1591. *
  1592. * @param {NodeBuilder} builder - The current node builder.
  1593. * @return {String} The component type.
  1594. */
  1595. getComponentType( builder ) {
  1596. return builder.getComponentType( this.node.getNodeType( builder ) );
  1597. }
  1598. /**
  1599. * This method is overwritten since the node type is inferred from requested components.
  1600. *
  1601. * @param {NodeBuilder} builder - The current node builder.
  1602. * @return {String} The node type.
  1603. */
  1604. getNodeType( builder ) {
  1605. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1606. }
  1607. generate( builder, output ) {
  1608. const node = this.node;
  1609. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1610. let snippet = null;
  1611. if ( nodeTypeLength > 1 ) {
  1612. let type = null;
  1613. const componentsLength = this.getVectorLength();
  1614. if ( componentsLength >= nodeTypeLength ) {
  1615. // needed expand the input node
  1616. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1617. }
  1618. const nodeSnippet = node.build( builder, type );
  1619. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1620. // unnecessary swizzle
  1621. snippet = builder.format( nodeSnippet, type, output );
  1622. } else {
  1623. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1624. }
  1625. } else {
  1626. // ignore .components if .node returns float/integer
  1627. snippet = node.build( builder, output );
  1628. }
  1629. return snippet;
  1630. }
  1631. serialize( data ) {
  1632. super.serialize( data );
  1633. data.components = this.components;
  1634. }
  1635. deserialize( data ) {
  1636. super.deserialize( data );
  1637. this.components = data.components;
  1638. }
  1639. }
  1640. /**
  1641. * This module is part of the TSL core and usually not used in app level code.
  1642. * `SetNode` represents a set operation which means it is used to implement any
  1643. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1644. * For example:
  1645. * ```js
  1646. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1647. * ```
  1648. *
  1649. * @augments TempNode
  1650. */
  1651. class SetNode extends TempNode {
  1652. static get type() {
  1653. return 'SetNode';
  1654. }
  1655. /**
  1656. * Constructs a new set node.
  1657. *
  1658. * @param {Node} sourceNode - The node that should be updated.
  1659. * @param {String} components - The components that should be updated.
  1660. * @param {Node} targetNode - The value node.
  1661. */
  1662. constructor( sourceNode, components, targetNode ) {
  1663. super();
  1664. /**
  1665. * The node that should be updated.
  1666. *
  1667. * @type {Node}
  1668. */
  1669. this.sourceNode = sourceNode;
  1670. /**
  1671. * The components that should be updated.
  1672. *
  1673. * @type {String}
  1674. */
  1675. this.components = components;
  1676. /**
  1677. * The value node.
  1678. *
  1679. * @type {Node}
  1680. */
  1681. this.targetNode = targetNode;
  1682. }
  1683. /**
  1684. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1685. *
  1686. * @param {NodeBuilder} builder - The current node builder.
  1687. * @return {String} The node type.
  1688. */
  1689. getNodeType( builder ) {
  1690. return this.sourceNode.getNodeType( builder );
  1691. }
  1692. generate( builder ) {
  1693. const { sourceNode, components, targetNode } = this;
  1694. const sourceType = this.getNodeType( builder );
  1695. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1696. const targetType = builder.getTypeFromLength( components.length, componentType );
  1697. const targetSnippet = targetNode.build( builder, targetType );
  1698. const sourceSnippet = sourceNode.build( builder, sourceType );
  1699. const length = builder.getTypeLength( sourceType );
  1700. const snippetValues = [];
  1701. for ( let i = 0; i < length; i ++ ) {
  1702. const component = vectorComponents[ i ];
  1703. if ( component === components[ 0 ] ) {
  1704. snippetValues.push( targetSnippet );
  1705. i += components.length - 1;
  1706. } else {
  1707. snippetValues.push( sourceSnippet + '.' + component );
  1708. }
  1709. }
  1710. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1711. }
  1712. }
  1713. /**
  1714. * This module is part of the TSL core and usually not used in app level code.
  1715. * It represents a flip operation during the shader generation process
  1716. * meaning it flips normalized values with the following formula:
  1717. * ```
  1718. * x = 1 - x;
  1719. * ```
  1720. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1721. * `flipSTPQ()` method invocations on node objects. For example:
  1722. * ```js
  1723. * uvNode = uvNode.flipY();
  1724. * ```
  1725. *
  1726. * @augments TempNode
  1727. */
  1728. class FlipNode extends TempNode {
  1729. static get type() {
  1730. return 'FlipNode';
  1731. }
  1732. /**
  1733. * Constructs a new flip node.
  1734. *
  1735. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1736. * @param {String} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1737. */
  1738. constructor( sourceNode, components ) {
  1739. super();
  1740. /**
  1741. * The node which component(s) should be flipped.
  1742. *
  1743. * @type {Node}
  1744. */
  1745. this.sourceNode = sourceNode;
  1746. /**
  1747. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1748. *
  1749. * @type {String}
  1750. */
  1751. this.components = components;
  1752. }
  1753. /**
  1754. * This method is overwritten since the node type is inferred from the source node.
  1755. *
  1756. * @param {NodeBuilder} builder - The current node builder.
  1757. * @return {String} The node type.
  1758. */
  1759. getNodeType( builder ) {
  1760. return this.sourceNode.getNodeType( builder );
  1761. }
  1762. generate( builder ) {
  1763. const { components, sourceNode } = this;
  1764. const sourceType = this.getNodeType( builder );
  1765. const sourceSnippet = sourceNode.build( builder );
  1766. const sourceCache = builder.getVarFromNode( this );
  1767. const sourceProperty = builder.getPropertyName( sourceCache );
  1768. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1769. const length = builder.getTypeLength( sourceType );
  1770. const snippetValues = [];
  1771. let componentIndex = 0;
  1772. for ( let i = 0; i < length; i ++ ) {
  1773. const component = vectorComponents[ i ];
  1774. if ( component === components[ componentIndex ] ) {
  1775. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1776. componentIndex ++;
  1777. } else {
  1778. snippetValues.push( sourceProperty + '.' + component );
  1779. }
  1780. }
  1781. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1782. }
  1783. }
  1784. /**
  1785. * Base class for representing data input nodes.
  1786. *
  1787. * @augments Node
  1788. */
  1789. class InputNode extends Node {
  1790. static get type() {
  1791. return 'InputNode';
  1792. }
  1793. /**
  1794. * Constructs a new input node.
  1795. *
  1796. * @param {Any} value - The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1797. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1798. */
  1799. constructor( value, nodeType = null ) {
  1800. super( nodeType );
  1801. /**
  1802. * This flag can be used for type testing.
  1803. *
  1804. * @type {Boolean}
  1805. * @readonly
  1806. * @default true
  1807. */
  1808. this.isInputNode = true;
  1809. /**
  1810. * The value of this node. This can be a any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1811. *
  1812. * @type {Any}
  1813. */
  1814. this.value = value;
  1815. /**
  1816. * The precision of the value in the shader.
  1817. *
  1818. * @type {('low'|'medium'|'high')?}
  1819. * @default null
  1820. */
  1821. this.precision = null;
  1822. }
  1823. getNodeType( /*builder*/ ) {
  1824. if ( this.nodeType === null ) {
  1825. return getValueType( this.value );
  1826. }
  1827. return this.nodeType;
  1828. }
  1829. /**
  1830. * Returns the input type of the node which is by default the node type. Derived modules
  1831. * might overwrite this method and use a fixed type or compute one analytically.
  1832. *
  1833. * A typical example for different input and node types are textures. The input type of a
  1834. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1835. *
  1836. * @param {NodeBuilder} builder - The current node builder.
  1837. * @return {String} The input type.
  1838. */
  1839. getInputType( builder ) {
  1840. return this.getNodeType( builder );
  1841. }
  1842. /**
  1843. * Sets the precision to the given value. The method can be
  1844. * overwritten in derived classes if the final precision must be computed
  1845. * analytically.
  1846. *
  1847. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1848. * @return {InputNode} A reference to this node.
  1849. */
  1850. setPrecision( precision ) {
  1851. this.precision = precision;
  1852. return this;
  1853. }
  1854. serialize( data ) {
  1855. super.serialize( data );
  1856. data.value = this.value;
  1857. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1858. data.valueType = getValueType( this.value );
  1859. data.nodeType = this.nodeType;
  1860. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1861. data.precision = this.precision;
  1862. }
  1863. deserialize( data ) {
  1864. super.deserialize( data );
  1865. this.nodeType = data.nodeType;
  1866. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1867. this.precision = data.precision || null;
  1868. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1869. }
  1870. generate( /*builder, output*/ ) {
  1871. console.warn( 'Abstract function.' );
  1872. }
  1873. }
  1874. /**
  1875. * Class for representing a constant value in the shader.
  1876. *
  1877. * @augments InputNode
  1878. */
  1879. class ConstNode extends InputNode {
  1880. static get type() {
  1881. return 'ConstNode';
  1882. }
  1883. /**
  1884. * Constructs a new input node.
  1885. *
  1886. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  1887. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1888. */
  1889. constructor( value, nodeType = null ) {
  1890. super( value, nodeType );
  1891. /**
  1892. * This flag can be used for type testing.
  1893. *
  1894. * @type {Boolean}
  1895. * @readonly
  1896. * @default true
  1897. */
  1898. this.isConstNode = true;
  1899. }
  1900. /**
  1901. * Generates the shader string of the value with the current node builder.
  1902. *
  1903. * @param {NodeBuilder} builder - The current node builder.
  1904. * @return {String} The generated value as a shader string.
  1905. */
  1906. generateConst( builder ) {
  1907. return builder.generateConst( this.getNodeType( builder ), this.value );
  1908. }
  1909. generate( builder, output ) {
  1910. const type = this.getNodeType( builder );
  1911. return builder.format( this.generateConst( builder ), type, output );
  1912. }
  1913. }
  1914. /** @module TSLCore **/
  1915. let currentStack = null;
  1916. const NodeElements = new Map();
  1917. function addMethodChaining( name, nodeElement ) {
  1918. if ( NodeElements.has( name ) ) {
  1919. console.warn( `Redefinition of method chaining ${ name }` );
  1920. return;
  1921. }
  1922. if ( typeof nodeElement !== 'function' ) throw new Error( `Node element ${ name } is not a function` );
  1923. NodeElements.set( name, nodeElement );
  1924. }
  1925. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  1926. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  1927. const shaderNodeHandler = {
  1928. setup( NodeClosure, params ) {
  1929. const inputs = params.shift();
  1930. return NodeClosure( nodeObjects( inputs ), ...params );
  1931. },
  1932. get( node, prop, nodeObj ) {
  1933. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1934. if ( node.isStackNode !== true && prop === 'assign' ) {
  1935. return ( ...params ) => {
  1936. currentStack.assign( nodeObj, ...params );
  1937. return nodeObj;
  1938. };
  1939. } else if ( NodeElements.has( prop ) ) {
  1940. const nodeElement = NodeElements.get( prop );
  1941. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  1942. } else if ( prop === 'self' ) {
  1943. return node;
  1944. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  1945. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  1946. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  1947. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  1948. // accessing properties ( swizzle )
  1949. prop = parseSwizzle( prop );
  1950. return nodeObject( new SplitNode( nodeObj, prop ) );
  1951. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1952. // set properties ( swizzle ) and sort to xyzw sequence
  1953. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  1954. return ( value ) => nodeObject( new SetNode( node, prop, value ) );
  1955. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  1956. // set properties ( swizzle ) and sort to xyzw sequence
  1957. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  1958. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  1959. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  1960. // accessing property
  1961. if ( prop === 'width' ) prop = 'x';
  1962. else if ( prop === 'height' ) prop = 'y';
  1963. else if ( prop === 'depth' ) prop = 'z';
  1964. return nodeObject( new SplitNode( node, prop ) );
  1965. } else if ( /^\d+$/.test( prop ) === true ) {
  1966. // accessing array
  1967. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  1968. }
  1969. }
  1970. return Reflect.get( node, prop, nodeObj );
  1971. },
  1972. set( node, prop, value, nodeObj ) {
  1973. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  1974. // setting properties
  1975. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  1976. nodeObj[ prop ].assign( value );
  1977. return true;
  1978. }
  1979. }
  1980. return Reflect.set( node, prop, value, nodeObj );
  1981. }
  1982. };
  1983. const nodeObjectsCacheMap = new WeakMap();
  1984. const nodeBuilderFunctionsCacheMap = new WeakMap();
  1985. const ShaderNodeObject = function ( obj, altType = null ) {
  1986. const type = getValueType( obj );
  1987. if ( type === 'node' ) {
  1988. let nodeObject = nodeObjectsCacheMap.get( obj );
  1989. if ( nodeObject === undefined ) {
  1990. nodeObject = new Proxy( obj, shaderNodeHandler );
  1991. nodeObjectsCacheMap.set( obj, nodeObject );
  1992. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  1993. }
  1994. return nodeObject;
  1995. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  1996. return nodeObject( getConstNode( obj, altType ) );
  1997. } else if ( type === 'shader' ) {
  1998. return Fn( obj );
  1999. }
  2000. return obj;
  2001. };
  2002. const ShaderNodeObjects = function ( objects, altType = null ) {
  2003. for ( const name in objects ) {
  2004. objects[ name ] = nodeObject( objects[ name ], altType );
  2005. }
  2006. return objects;
  2007. };
  2008. const ShaderNodeArray = function ( array, altType = null ) {
  2009. const len = array.length;
  2010. for ( let i = 0; i < len; i ++ ) {
  2011. array[ i ] = nodeObject( array[ i ], altType );
  2012. }
  2013. return array;
  2014. };
  2015. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2016. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2017. if ( scope === null ) {
  2018. return ( ...params ) => {
  2019. return assignNode( new NodeClass( ...nodeArray( params ) ) );
  2020. };
  2021. } else if ( factor !== null ) {
  2022. factor = nodeObject( factor );
  2023. return ( ...params ) => {
  2024. return assignNode( new NodeClass( scope, ...nodeArray( params ), factor ) );
  2025. };
  2026. } else {
  2027. return ( ...params ) => {
  2028. return assignNode( new NodeClass( scope, ...nodeArray( params ) ) );
  2029. };
  2030. }
  2031. };
  2032. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2033. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2034. };
  2035. class ShaderCallNodeInternal extends Node {
  2036. constructor( shaderNode, inputNodes ) {
  2037. super();
  2038. this.shaderNode = shaderNode;
  2039. this.inputNodes = inputNodes;
  2040. }
  2041. getNodeType( builder ) {
  2042. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2043. }
  2044. call( builder ) {
  2045. const { shaderNode, inputNodes } = this;
  2046. const properties = builder.getNodeProperties( shaderNode );
  2047. if ( properties.onceOutput ) return properties.onceOutput;
  2048. //
  2049. let result = null;
  2050. if ( shaderNode.layout ) {
  2051. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2052. if ( functionNodesCacheMap === undefined ) {
  2053. functionNodesCacheMap = new WeakMap();
  2054. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2055. }
  2056. let functionNode = functionNodesCacheMap.get( shaderNode );
  2057. if ( functionNode === undefined ) {
  2058. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2059. functionNodesCacheMap.set( shaderNode, functionNode );
  2060. }
  2061. if ( builder.currentFunctionNode !== null ) {
  2062. builder.currentFunctionNode.includes.push( functionNode );
  2063. }
  2064. result = nodeObject( functionNode.call( inputNodes ) );
  2065. } else {
  2066. const jsFunc = shaderNode.jsFunc;
  2067. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2068. result = nodeObject( outputNode );
  2069. }
  2070. if ( shaderNode.once ) {
  2071. properties.onceOutput = result;
  2072. }
  2073. return result;
  2074. }
  2075. getOutputNode( builder ) {
  2076. const properties = builder.getNodeProperties( this );
  2077. if ( properties.outputNode === null ) {
  2078. properties.outputNode = this.setupOutput( builder );
  2079. }
  2080. return properties.outputNode;
  2081. }
  2082. setup( builder ) {
  2083. return this.getOutputNode( builder );
  2084. }
  2085. setupOutput( builder ) {
  2086. builder.addStack();
  2087. builder.stack.outputNode = this.call( builder );
  2088. return builder.removeStack();
  2089. }
  2090. generate( builder, output ) {
  2091. const outputNode = this.getOutputNode( builder );
  2092. return outputNode.build( builder, output );
  2093. }
  2094. }
  2095. class ShaderNodeInternal extends Node {
  2096. constructor( jsFunc, nodeType ) {
  2097. super( nodeType );
  2098. this.jsFunc = jsFunc;
  2099. this.layout = null;
  2100. this.global = true;
  2101. this.once = false;
  2102. }
  2103. setLayout( layout ) {
  2104. this.layout = layout;
  2105. return this;
  2106. }
  2107. call( inputs = null ) {
  2108. nodeObjects( inputs );
  2109. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2110. }
  2111. setup() {
  2112. return this.call();
  2113. }
  2114. }
  2115. const bools = [ false, true ];
  2116. const uints = [ 0, 1, 2, 3 ];
  2117. const ints = [ - 1, - 2 ];
  2118. const floats = [ 0.5, 1.5, 1 / 3, 1e-6, 1e6, Math.PI, Math.PI * 2, 1 / Math.PI, 2 / Math.PI, 1 / ( Math.PI * 2 ), Math.PI / 2 ];
  2119. const boolsCacheMap = new Map();
  2120. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2121. const uintsCacheMap = new Map();
  2122. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2123. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2124. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2125. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2126. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2127. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2128. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2129. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2130. const getConstNode = ( value, type ) => {
  2131. if ( constNodesCacheMap.has( value ) ) {
  2132. return constNodesCacheMap.get( value );
  2133. } else if ( value.isNode === true ) {
  2134. return value;
  2135. } else {
  2136. return new ConstNode( value, type );
  2137. }
  2138. };
  2139. const safeGetNodeType = ( node ) => {
  2140. try {
  2141. return node.getNodeType();
  2142. } catch ( _ ) {
  2143. return undefined;
  2144. }
  2145. };
  2146. const ConvertType = function ( type, cacheMap = null ) {
  2147. return ( ...params ) => {
  2148. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2149. params = [ getValueFromType( type, ...params ) ];
  2150. }
  2151. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2152. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2153. }
  2154. if ( params.length === 1 ) {
  2155. const node = getConstNode( params[ 0 ], type );
  2156. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2157. return nodeObject( new ConvertNode( node, type ) );
  2158. }
  2159. const nodes = params.map( param => getConstNode( param ) );
  2160. return nodeObject( new JoinNode( nodes, type ) );
  2161. };
  2162. };
  2163. // exports
  2164. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2165. // utils
  2166. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2167. // shader node base
  2168. function ShaderNode( jsFunc, nodeType ) {
  2169. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2170. }
  2171. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2172. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2173. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2174. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2175. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2176. const Fn = ( jsFunc, nodeType ) => {
  2177. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2178. const fn = ( ...params ) => {
  2179. let inputs;
  2180. nodeObjects( params );
  2181. if ( params[ 0 ] && params[ 0 ].isNode ) {
  2182. inputs = [ ...params ];
  2183. } else {
  2184. inputs = params[ 0 ];
  2185. }
  2186. return shaderNode.call( inputs );
  2187. };
  2188. fn.shaderNode = shaderNode;
  2189. fn.setLayout = ( layout ) => {
  2190. shaderNode.setLayout( layout );
  2191. return fn;
  2192. };
  2193. fn.once = () => {
  2194. shaderNode.once = true;
  2195. return fn;
  2196. };
  2197. return fn;
  2198. };
  2199. /**
  2200. * @function
  2201. * @deprecated since r168. Use {@link Fn} instead.
  2202. *
  2203. * @param {...any} params
  2204. * @returns {Function}
  2205. */
  2206. const tslFn = ( ...params ) => { // @deprecated, r168
  2207. console.warn( 'TSL.ShaderNode: tslFn() has been renamed to Fn().' );
  2208. return Fn( ...params );
  2209. };
  2210. //
  2211. addMethodChaining( 'toGlobal', ( node ) => {
  2212. node.global = true;
  2213. return node;
  2214. } );
  2215. //
  2216. const setCurrentStack = ( stack ) => {
  2217. currentStack = stack;
  2218. };
  2219. const getCurrentStack = () => currentStack;
  2220. const If = ( ...params ) => currentStack.If( ...params );
  2221. function append( node ) {
  2222. if ( currentStack ) currentStack.add( node );
  2223. return node;
  2224. }
  2225. addMethodChaining( 'append', append );
  2226. // types
  2227. const color = new ConvertType( 'color' );
  2228. const float = new ConvertType( 'float', cacheMaps.float );
  2229. const int = new ConvertType( 'int', cacheMaps.ints );
  2230. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2231. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2232. const vec2 = new ConvertType( 'vec2' );
  2233. const ivec2 = new ConvertType( 'ivec2' );
  2234. const uvec2 = new ConvertType( 'uvec2' );
  2235. const bvec2 = new ConvertType( 'bvec2' );
  2236. const vec3 = new ConvertType( 'vec3' );
  2237. const ivec3 = new ConvertType( 'ivec3' );
  2238. const uvec3 = new ConvertType( 'uvec3' );
  2239. const bvec3 = new ConvertType( 'bvec3' );
  2240. const vec4 = new ConvertType( 'vec4' );
  2241. const ivec4 = new ConvertType( 'ivec4' );
  2242. const uvec4 = new ConvertType( 'uvec4' );
  2243. const bvec4 = new ConvertType( 'bvec4' );
  2244. const mat2 = new ConvertType( 'mat2' );
  2245. const mat3 = new ConvertType( 'mat3' );
  2246. const mat4 = new ConvertType( 'mat4' );
  2247. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2248. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2249. addMethodChaining( 'toColor', color );
  2250. addMethodChaining( 'toFloat', float );
  2251. addMethodChaining( 'toInt', int );
  2252. addMethodChaining( 'toUint', uint );
  2253. addMethodChaining( 'toBool', bool );
  2254. addMethodChaining( 'toVec2', vec2 );
  2255. addMethodChaining( 'toIVec2', ivec2 );
  2256. addMethodChaining( 'toUVec2', uvec2 );
  2257. addMethodChaining( 'toBVec2', bvec2 );
  2258. addMethodChaining( 'toVec3', vec3 );
  2259. addMethodChaining( 'toIVec3', ivec3 );
  2260. addMethodChaining( 'toUVec3', uvec3 );
  2261. addMethodChaining( 'toBVec3', bvec3 );
  2262. addMethodChaining( 'toVec4', vec4 );
  2263. addMethodChaining( 'toIVec4', ivec4 );
  2264. addMethodChaining( 'toUVec4', uvec4 );
  2265. addMethodChaining( 'toBVec4', bvec4 );
  2266. addMethodChaining( 'toMat2', mat2 );
  2267. addMethodChaining( 'toMat3', mat3 );
  2268. addMethodChaining( 'toMat4', mat4 );
  2269. // basic nodes
  2270. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode );
  2271. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2272. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2273. addMethodChaining( 'element', element );
  2274. addMethodChaining( 'convert', convert );
  2275. /** @module UniformGroupNode **/
  2276. /**
  2277. * This node can be used to group single instances of {@link UniformNode}
  2278. * and manage them as a uniform buffer.
  2279. *
  2280. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2281. * will be used when defining the {@link UniformNode#groupNode} property.
  2282. *
  2283. * - `objectGroup`: Uniform buffer per object.
  2284. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2285. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2286. *
  2287. * @augments Node
  2288. */
  2289. class UniformGroupNode extends Node {
  2290. static get type() {
  2291. return 'UniformGroupNode';
  2292. }
  2293. /**
  2294. * Constructs a new uniform group node.
  2295. *
  2296. * @param {String} name - The name of the uniform group node.
  2297. * @param {Boolean} [shared=false] - Whether this uniform group node is shared or not.
  2298. * @param {Number} [order=1] - Influences the internal sorting.
  2299. */
  2300. constructor( name, shared = false, order = 1 ) {
  2301. super( 'string' );
  2302. /**
  2303. * The name of the uniform group node.
  2304. *
  2305. * @type {String}
  2306. */
  2307. this.name = name;
  2308. /**
  2309. * Whether this uniform group node is shared or not.
  2310. *
  2311. * @type {Boolean}
  2312. * @default false
  2313. */
  2314. this.shared = shared;
  2315. /**
  2316. * Influences the internal sorting.
  2317. * TODO: Add details when this property should be changed.
  2318. *
  2319. * @type {Number}
  2320. * @default 1
  2321. */
  2322. this.order = order;
  2323. /**
  2324. * This flag can be used for type testing.
  2325. *
  2326. * @type {Boolean}
  2327. * @readonly
  2328. * @default true
  2329. */
  2330. this.isUniformGroup = true;
  2331. }
  2332. serialize( data ) {
  2333. super.serialize( data );
  2334. data.name = this.name;
  2335. data.version = this.version;
  2336. data.shared = this.shared;
  2337. }
  2338. deserialize( data ) {
  2339. super.deserialize( data );
  2340. this.name = data.name;
  2341. this.version = data.version;
  2342. this.shared = data.shared;
  2343. }
  2344. }
  2345. /**
  2346. * TSL function for creating a uniform group node with the given name.
  2347. *
  2348. * @function
  2349. * @param {String} name - The name of the uniform group node.
  2350. * @returns {UniformGroupNode}
  2351. */
  2352. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2353. /**
  2354. * TSL function for creating a shared uniform group node with the given name and order.
  2355. *
  2356. * @function
  2357. * @param {String} name - The name of the uniform group node.
  2358. * @param {Number} [order=0] - Influences the internal sorting.
  2359. * @returns {UniformGroupNode}
  2360. */
  2361. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2362. /**
  2363. * TSL object that represents a shared uniform group node which is updated once per frame.
  2364. *
  2365. * @type {UniformGroupNode}
  2366. */
  2367. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2368. /**
  2369. * TSL object that represents a shared uniform group node which is updated once per render.
  2370. *
  2371. * @type {UniformGroupNode}
  2372. */
  2373. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2374. /**
  2375. * TSL object that represents a uniform group node which is updated once per object.
  2376. *
  2377. * @type {UniformGroupNode}
  2378. */
  2379. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2380. /** @module UniformNode **/
  2381. /**
  2382. * Class for representing a uniform.
  2383. *
  2384. * @augments InputNode
  2385. */
  2386. class UniformNode extends InputNode {
  2387. static get type() {
  2388. return 'UniformNode';
  2389. }
  2390. /**
  2391. * Constructs a new uniform node.
  2392. *
  2393. * @param {Any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2394. * @param {String?} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2395. */
  2396. constructor( value, nodeType = null ) {
  2397. super( value, nodeType );
  2398. /**
  2399. * This flag can be used for type testing.
  2400. *
  2401. * @type {Boolean}
  2402. * @readonly
  2403. * @default true
  2404. */
  2405. this.isUniformNode = true;
  2406. /**
  2407. * The name or label of the uniform.
  2408. *
  2409. * @type {String}
  2410. * @default ''
  2411. */
  2412. this.name = '';
  2413. /**
  2414. * The uniform group of this uniform. By default, uniforms are
  2415. * managed per object but they might belong to a shared group
  2416. * which is updated per frame or render call.
  2417. *
  2418. * @type {UniformGroupNode}
  2419. */
  2420. this.groupNode = objectGroup;
  2421. }
  2422. /**
  2423. * Sets the {@link UniformNode#name} property.
  2424. *
  2425. * @param {String} name - The name of the uniform.
  2426. * @return {UniformNode} A reference to this node.
  2427. */
  2428. label( name ) {
  2429. this.name = name;
  2430. return this;
  2431. }
  2432. /**
  2433. * Sets the {@link UniformNode#groupNode} property.
  2434. *
  2435. * @param {UniformGroupNode} group - The uniform group.
  2436. * @return {UniformNode} A reference to this node.
  2437. */
  2438. setGroup( group ) {
  2439. this.groupNode = group;
  2440. return this;
  2441. }
  2442. /**
  2443. * Returns the {@link UniformNode#groupNode}.
  2444. *
  2445. * @return {UniformGroupNode} The uniform group.
  2446. */
  2447. getGroup() {
  2448. return this.groupNode;
  2449. }
  2450. /**
  2451. * By default, this method returns the result of {@link Node#getHash} but derived
  2452. * classes might overwrite this method with a different implementation.
  2453. *
  2454. * @param {NodeBuilder} builder - The current node builder.
  2455. * @return {String} The uniform hash.
  2456. */
  2457. getUniformHash( builder ) {
  2458. return this.getHash( builder );
  2459. }
  2460. onUpdate( callback, updateType ) {
  2461. const self = this.getSelf();
  2462. callback = callback.bind( self );
  2463. return super.onUpdate( ( frame ) => {
  2464. const value = callback( frame, self );
  2465. if ( value !== undefined ) {
  2466. this.value = value;
  2467. }
  2468. }, updateType );
  2469. }
  2470. generate( builder, output ) {
  2471. const type = this.getNodeType( builder );
  2472. const hash = this.getUniformHash( builder );
  2473. let sharedNode = builder.getNodeFromHash( hash );
  2474. if ( sharedNode === undefined ) {
  2475. builder.setHashNode( this, hash );
  2476. sharedNode = this;
  2477. }
  2478. const sharedNodeType = sharedNode.getInputType( builder );
  2479. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  2480. const propertyName = builder.getPropertyName( nodeUniform );
  2481. if ( builder.context.label !== undefined ) delete builder.context.label;
  2482. return builder.format( propertyName, type, output );
  2483. }
  2484. }
  2485. /**
  2486. * TSL function for creating a uniform node.
  2487. *
  2488. * @function
  2489. * @param {Any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2490. * @param {String?} arg2 - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2491. * @returns {UniformNode}
  2492. */
  2493. const uniform = ( arg1, arg2 ) => {
  2494. const nodeType = getConstNodeType( arg2 || arg1 );
  2495. // @TODO: get ConstNode from .traverse() in the future
  2496. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  2497. return nodeObject( new UniformNode( value, nodeType ) );
  2498. };
  2499. /** @module PropertyNode **/
  2500. /**
  2501. * This class represents a shader property. It can be used
  2502. * to explicitly define a property and assign a value to it.
  2503. *
  2504. * ```js
  2505. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2506. *```
  2507. * `PropertyNode` is used by the engine to predefined common material properties
  2508. * for TSL code.
  2509. *
  2510. * @augments Node
  2511. */
  2512. class PropertyNode extends Node {
  2513. static get type() {
  2514. return 'PropertyNode';
  2515. }
  2516. /**
  2517. * Constructs a new property node.
  2518. *
  2519. * @param {String} nodeType - The type of the node.
  2520. * @param {String?} [name=null] - The name of the property in the shader.
  2521. * @param {Boolean} [varying=false] - Whether this property is a varying or not.
  2522. */
  2523. constructor( nodeType, name = null, varying = false ) {
  2524. super( nodeType );
  2525. /**
  2526. * The name of the property in the shader. If no name is defined,
  2527. * the node system auto-generates one.
  2528. *
  2529. * @type {String?}
  2530. * @default null
  2531. */
  2532. this.name = name;
  2533. /**
  2534. * Whether this property is a varying or not.
  2535. *
  2536. * @type {Boolean}
  2537. * @default false
  2538. */
  2539. this.varying = varying;
  2540. /**
  2541. * This flag can be used for type testing.
  2542. *
  2543. * @type {Boolean}
  2544. * @readonly
  2545. * @default true
  2546. */
  2547. this.isPropertyNode = true;
  2548. }
  2549. getHash( builder ) {
  2550. return this.name || super.getHash( builder );
  2551. }
  2552. /**
  2553. * The method is overwritten so it always returns `true`.
  2554. *
  2555. * @param {NodeBuilder} builder - The current node builder.
  2556. * @return {Boolean} Whether this node is global or not.
  2557. */
  2558. isGlobal( /*builder*/ ) {
  2559. return true;
  2560. }
  2561. generate( builder ) {
  2562. let nodeVar;
  2563. if ( this.varying === true ) {
  2564. nodeVar = builder.getVaryingFromNode( this, this.name );
  2565. nodeVar.needsInterpolation = true;
  2566. } else {
  2567. nodeVar = builder.getVarFromNode( this, this.name );
  2568. }
  2569. return builder.getPropertyName( nodeVar );
  2570. }
  2571. }
  2572. /**
  2573. * TSL function for creating a property node.
  2574. *
  2575. * @function
  2576. * @param {String} type - The type of the node.
  2577. * @param {String?} [name=null] - The name of the property in the shader.
  2578. * @returns {PropertyNode}
  2579. */
  2580. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2581. /**
  2582. * TSL function for creating a varying property node.
  2583. *
  2584. * @function
  2585. * @param {String} type - The type of the node.
  2586. * @param {String?} [name=null] - The name of the varying in the shader.
  2587. * @returns {PropertyNode}
  2588. */
  2589. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2590. /**
  2591. * TSL object that represents the shader variable `DiffuseColor`.
  2592. *
  2593. * @type {PropertyNode<vec4>}
  2594. */
  2595. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2596. /**
  2597. * TSL object that represents the shader variable `EmissiveColor`.
  2598. *
  2599. * @type {PropertyNode<vec3>}
  2600. */
  2601. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2602. /**
  2603. * TSL object that represents the shader variable `Roughness`.
  2604. *
  2605. * @type {PropertyNode<float>}
  2606. */
  2607. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2608. /**
  2609. * TSL object that represents the shader variable `Metalness`.
  2610. *
  2611. * @type {PropertyNode<float>}
  2612. */
  2613. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2614. /**
  2615. * TSL object that represents the shader variable `Clearcoat`.
  2616. *
  2617. * @type {PropertyNode<float>}
  2618. */
  2619. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2620. /**
  2621. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2622. *
  2623. * @type {PropertyNode<float>}
  2624. */
  2625. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2626. /**
  2627. * TSL object that represents the shader variable `Sheen`.
  2628. *
  2629. * @type {PropertyNode<vec3>}
  2630. */
  2631. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2632. /**
  2633. * TSL object that represents the shader variable `SheenRoughness`.
  2634. *
  2635. * @type {PropertyNode<float>}
  2636. */
  2637. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2638. /**
  2639. * TSL object that represents the shader variable `Iridescence`.
  2640. *
  2641. * @type {PropertyNode<float>}
  2642. */
  2643. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2644. /**
  2645. * TSL object that represents the shader variable `IridescenceIOR`.
  2646. *
  2647. * @type {PropertyNode<float>}
  2648. */
  2649. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2650. /**
  2651. * TSL object that represents the shader variable `IridescenceThickness`.
  2652. *
  2653. * @type {PropertyNode<float>}
  2654. */
  2655. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2656. /**
  2657. * TSL object that represents the shader variable `AlphaT`.
  2658. *
  2659. * @type {PropertyNode<float>}
  2660. */
  2661. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2662. /**
  2663. * TSL object that represents the shader variable `Anisotropy`.
  2664. *
  2665. * @type {PropertyNode<float>}
  2666. */
  2667. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2668. /**
  2669. * TSL object that represents the shader variable `AnisotropyT`.
  2670. *
  2671. * @type {PropertyNode<vec3>}
  2672. */
  2673. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2674. /**
  2675. * TSL object that represents the shader variable `AnisotropyB`.
  2676. *
  2677. * @type {PropertyNode<vec3>}
  2678. */
  2679. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2680. /**
  2681. * TSL object that represents the shader variable `SpecularColor`.
  2682. *
  2683. * @type {PropertyNode<color>}
  2684. */
  2685. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2686. /**
  2687. * TSL object that represents the shader variable `SpecularF90`.
  2688. *
  2689. * @type {PropertyNode<float>}
  2690. */
  2691. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2692. /**
  2693. * TSL object that represents the shader variable `Shininess`.
  2694. *
  2695. * @type {PropertyNode<float>}
  2696. */
  2697. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2698. /**
  2699. * TSL object that represents the shader variable `Output`.
  2700. *
  2701. * @type {PropertyNode<vec4>}
  2702. */
  2703. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2704. /**
  2705. * TSL object that represents the shader variable `dashSize`.
  2706. *
  2707. * @type {PropertyNode<float>}
  2708. */
  2709. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2710. /**
  2711. * TSL object that represents the shader variable `gapSize`.
  2712. *
  2713. * @type {PropertyNode<float>}
  2714. */
  2715. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2716. /**
  2717. * TSL object that represents the shader variable `pointWidth`.
  2718. *
  2719. * @type {PropertyNode<float>}
  2720. */
  2721. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2722. /**
  2723. * TSL object that represents the shader variable `IOR`.
  2724. *
  2725. * @type {PropertyNode<float>}
  2726. */
  2727. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2728. /**
  2729. * TSL object that represents the shader variable `Transmission`.
  2730. *
  2731. * @type {PropertyNode<float>}
  2732. */
  2733. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2734. /**
  2735. * TSL object that represents the shader variable `Thickness`.
  2736. *
  2737. * @type {PropertyNode<float>}
  2738. */
  2739. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2740. /**
  2741. * TSL object that represents the shader variable `AttenuationDistance`.
  2742. *
  2743. * @type {PropertyNode<float>}
  2744. */
  2745. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2746. /**
  2747. * TSL object that represents the shader variable `AttenuationColor`.
  2748. *
  2749. * @type {PropertyNode<color>}
  2750. */
  2751. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2752. /**
  2753. * TSL object that represents the shader variable `Dispersion`.
  2754. *
  2755. * @type {PropertyNode<float>}
  2756. */
  2757. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2758. /** @module AssignNode **/
  2759. /**
  2760. * These node represents an assign operation. Meaning a node is assigned
  2761. * to another node.
  2762. *
  2763. * @augments TempNode
  2764. */
  2765. class AssignNode extends TempNode {
  2766. static get type() {
  2767. return 'AssignNode';
  2768. }
  2769. /**
  2770. * Constructs a new assign node.
  2771. *
  2772. * @param {Node} targetNode - The target node.
  2773. * @param {Node} sourceNode - The source type.
  2774. */
  2775. constructor( targetNode, sourceNode ) {
  2776. super();
  2777. /**
  2778. * The target node.
  2779. *
  2780. * @type {Node}
  2781. */
  2782. this.targetNode = targetNode;
  2783. /**
  2784. * The source node.
  2785. *
  2786. * @type {Node}
  2787. */
  2788. this.sourceNode = sourceNode;
  2789. }
  2790. /**
  2791. * Whether this node is used more than once in context of other nodes. This method
  2792. * is overwritten since it always returns `false` (assigns are unique).
  2793. *
  2794. * @return {Boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  2795. */
  2796. hasDependencies() {
  2797. return false;
  2798. }
  2799. getNodeType( builder, output ) {
  2800. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  2801. }
  2802. /**
  2803. * Whether a split is required when assigning source to target. This can happen when the component length of
  2804. * target and source data type does not match.
  2805. *
  2806. * @param {NodeBuilder} builder - The current node builder.
  2807. * @return {Boolean} Whether a split is required when assigning source to target.
  2808. */
  2809. needsSplitAssign( builder ) {
  2810. const { targetNode } = this;
  2811. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  2812. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  2813. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  2814. return assignDifferentVector;
  2815. }
  2816. return false;
  2817. }
  2818. generate( builder, output ) {
  2819. const { targetNode, sourceNode } = this;
  2820. const needsSplitAssign = this.needsSplitAssign( builder );
  2821. const targetType = targetNode.getNodeType( builder );
  2822. const target = targetNode.context( { assign: true } ).build( builder );
  2823. const source = sourceNode.build( builder, targetType );
  2824. const sourceType = sourceNode.getNodeType( builder );
  2825. const nodeData = builder.getDataFromNode( this );
  2826. //
  2827. let snippet;
  2828. if ( nodeData.initialized === true ) {
  2829. if ( output !== 'void' ) {
  2830. snippet = target;
  2831. }
  2832. } else if ( needsSplitAssign ) {
  2833. const sourceVar = builder.getVarFromNode( this, null, targetType );
  2834. const sourceProperty = builder.getPropertyName( sourceVar );
  2835. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  2836. const targetRoot = targetNode.node.context( { assign: true } ).build( builder );
  2837. for ( let i = 0; i < targetNode.components.length; i ++ ) {
  2838. const component = targetNode.components[ i ];
  2839. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  2840. }
  2841. if ( output !== 'void' ) {
  2842. snippet = target;
  2843. }
  2844. } else {
  2845. snippet = `${ target } = ${ source }`;
  2846. if ( output === 'void' || sourceType === 'void' ) {
  2847. builder.addLineFlowCode( snippet, this );
  2848. if ( output !== 'void' ) {
  2849. snippet = target;
  2850. }
  2851. }
  2852. }
  2853. nodeData.initialized = true;
  2854. return builder.format( snippet, targetType, output );
  2855. }
  2856. }
  2857. /**
  2858. * TSL function for creating an assign node.
  2859. *
  2860. * @function
  2861. * @param {Node} targetNode - The target node.
  2862. * @param {Node} sourceNode - The source type.
  2863. * @returns {AssignNode}
  2864. */
  2865. const assign = /*@__PURE__*/ nodeProxy( AssignNode );
  2866. addMethodChaining( 'assign', assign );
  2867. /**
  2868. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  2869. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  2870. * this logic.
  2871. *
  2872. * @augments TempNode
  2873. */
  2874. class FunctionCallNode extends TempNode {
  2875. static get type() {
  2876. return 'FunctionCallNode';
  2877. }
  2878. /**
  2879. * Constructs a new function call node.
  2880. *
  2881. * @param {FunctionNode?} functionNode - The function node.
  2882. * @param {Object<String, Node>} [parameters={}] - The parameters for the function call.
  2883. */
  2884. constructor( functionNode = null, parameters = {} ) {
  2885. super();
  2886. /**
  2887. * The function node.
  2888. *
  2889. * @type {FunctionNode}
  2890. * @default null
  2891. */
  2892. this.functionNode = functionNode;
  2893. /**
  2894. * The parameters of the function call.
  2895. *
  2896. * @type {Object<String, Node>}
  2897. * @default {}
  2898. */
  2899. this.parameters = parameters;
  2900. }
  2901. /**
  2902. * Sets the parameters of the function call node.
  2903. *
  2904. * @param {Object<String, Node>} parameters - The parameters to set.
  2905. * @return {FunctionCallNode} A reference to this node.
  2906. */
  2907. setParameters( parameters ) {
  2908. this.parameters = parameters;
  2909. return this;
  2910. }
  2911. /**
  2912. * Returns the parameters of the function call node.
  2913. *
  2914. * @return {Object<String, Node>} The parameters of this node.
  2915. */
  2916. getParameters() {
  2917. return this.parameters;
  2918. }
  2919. getNodeType( builder ) {
  2920. return this.functionNode.getNodeType( builder );
  2921. }
  2922. generate( builder ) {
  2923. const params = [];
  2924. const functionNode = this.functionNode;
  2925. const inputs = functionNode.getInputs( builder );
  2926. const parameters = this.parameters;
  2927. const generateInput = ( node, inputNode ) => {
  2928. const type = inputNode.type;
  2929. const pointer = type === 'pointer';
  2930. let output;
  2931. if ( pointer ) output = '&' + node.build( builder );
  2932. else output = node.build( builder, type );
  2933. return output;
  2934. };
  2935. if ( Array.isArray( parameters ) ) {
  2936. for ( let i = 0; i < parameters.length; i ++ ) {
  2937. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  2938. }
  2939. } else {
  2940. for ( const inputNode of inputs ) {
  2941. const node = parameters[ inputNode.name ];
  2942. if ( node !== undefined ) {
  2943. params.push( generateInput( node, inputNode ) );
  2944. } else {
  2945. throw new Error( `FunctionCallNode: Input '${inputNode.name}' not found in FunctionNode.` );
  2946. }
  2947. }
  2948. }
  2949. const functionName = functionNode.build( builder, 'property' );
  2950. return `${functionName}( ${params.join( ', ' )} )`;
  2951. }
  2952. }
  2953. const call = ( func, ...params ) => {
  2954. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  2955. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  2956. };
  2957. addMethodChaining( 'call', call );
  2958. /** @module OperatorNode **/
  2959. /**
  2960. * This node represents basic mathematical and logical operations like addition,
  2961. * subtraction or comparisons (e.g. `equal()`).
  2962. *
  2963. * @augments TempNode
  2964. */
  2965. class OperatorNode extends TempNode {
  2966. static get type() {
  2967. return 'OperatorNode';
  2968. }
  2969. /**
  2970. * Constructs a new operator node.
  2971. *
  2972. * @param {String} op - The operator.
  2973. * @param {Node} aNode - The first input.
  2974. * @param {Node} bNode - The second input.
  2975. * @param {...Node} params - Additional input parameters.
  2976. */
  2977. constructor( op, aNode, bNode, ...params ) {
  2978. super();
  2979. if ( params.length > 0 ) {
  2980. let finalOp = new OperatorNode( op, aNode, bNode );
  2981. for ( let i = 0; i < params.length - 1; i ++ ) {
  2982. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  2983. }
  2984. aNode = finalOp;
  2985. bNode = params[ params.length - 1 ];
  2986. }
  2987. /**
  2988. * The operator.
  2989. *
  2990. * @type {String}
  2991. */
  2992. this.op = op;
  2993. /**
  2994. * The first input.
  2995. *
  2996. * @type {Node}
  2997. */
  2998. this.aNode = aNode;
  2999. /**
  3000. * The second input.
  3001. *
  3002. * @type {Node}
  3003. */
  3004. this.bNode = bNode;
  3005. /**
  3006. * This flag can be used for type testing.
  3007. *
  3008. * @type {Boolean}
  3009. * @readonly
  3010. * @default true
  3011. */
  3012. this.isOperatorNode = true;
  3013. }
  3014. /**
  3015. * This method is overwritten since the node type is inferred from the operator
  3016. * and the input node types.
  3017. *
  3018. * @param {NodeBuilder} builder - The current node builder.
  3019. * @param {String} output - The current output string.
  3020. * @return {String} The node type.
  3021. */
  3022. getNodeType( builder, output ) {
  3023. const op = this.op;
  3024. const aNode = this.aNode;
  3025. const bNode = this.bNode;
  3026. const typeA = aNode.getNodeType( builder );
  3027. const typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3028. if ( typeA === 'void' || typeB === 'void' ) {
  3029. return 'void';
  3030. } else if ( op === '%' ) {
  3031. return typeA;
  3032. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3033. return builder.getIntegerType( typeA );
  3034. } else if ( op === '!' || op === '==' || op === '&&' || op === '||' || op === '^^' ) {
  3035. return 'bool';
  3036. } else if ( op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3037. const typeLength = output ? builder.getTypeLength( output ) : Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3038. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3039. } else {
  3040. if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3041. return typeB;
  3042. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3043. // matrix x vector
  3044. return builder.getVectorFromMatrix( typeA );
  3045. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3046. // vector x matrix
  3047. return builder.getVectorFromMatrix( typeB );
  3048. } else if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3049. // anytype x anytype: use the greater length vector
  3050. return typeB;
  3051. }
  3052. return typeA;
  3053. }
  3054. }
  3055. generate( builder, output ) {
  3056. const op = this.op;
  3057. const aNode = this.aNode;
  3058. const bNode = this.bNode;
  3059. const type = this.getNodeType( builder, output );
  3060. let typeA = null;
  3061. let typeB = null;
  3062. if ( type !== 'void' ) {
  3063. typeA = aNode.getNodeType( builder );
  3064. typeB = typeof bNode !== 'undefined' ? bNode.getNodeType( builder ) : null;
  3065. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' ) {
  3066. if ( builder.isVector( typeA ) ) {
  3067. typeB = typeA;
  3068. } else if ( typeA !== typeB ) {
  3069. typeA = typeB = 'float';
  3070. }
  3071. } else if ( op === '>>' || op === '<<' ) {
  3072. typeA = type;
  3073. typeB = builder.changeComponentType( typeB, 'uint' );
  3074. } else if ( builder.isMatrix( typeA ) && builder.isVector( typeB ) ) {
  3075. // matrix x vector
  3076. typeB = builder.getVectorFromMatrix( typeA );
  3077. } else if ( builder.isVector( typeA ) && builder.isMatrix( typeB ) ) {
  3078. // vector x matrix
  3079. typeA = builder.getVectorFromMatrix( typeB );
  3080. } else {
  3081. // anytype x anytype
  3082. typeA = typeB = type;
  3083. }
  3084. } else {
  3085. typeA = typeB = type;
  3086. }
  3087. const a = aNode.build( builder, typeA );
  3088. const b = typeof bNode !== 'undefined' ? bNode.build( builder, typeB ) : null;
  3089. const outputLength = builder.getTypeLength( output );
  3090. const fnOpSnippet = builder.getFunctionOperator( op );
  3091. if ( output !== 'void' ) {
  3092. if ( op === '<' && outputLength > 1 ) {
  3093. if ( builder.useComparisonMethod ) {
  3094. return builder.format( `${ builder.getMethod( 'lessThan', output ) }( ${ a }, ${ b } )`, type, output );
  3095. } else {
  3096. return builder.format( `( ${ a } < ${ b } )`, type, output );
  3097. }
  3098. } else if ( op === '<=' && outputLength > 1 ) {
  3099. if ( builder.useComparisonMethod ) {
  3100. return builder.format( `${ builder.getMethod( 'lessThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3101. } else {
  3102. return builder.format( `( ${ a } <= ${ b } )`, type, output );
  3103. }
  3104. } else if ( op === '>' && outputLength > 1 ) {
  3105. if ( builder.useComparisonMethod ) {
  3106. return builder.format( `${ builder.getMethod( 'greaterThan', output ) }( ${ a }, ${ b } )`, type, output );
  3107. } else {
  3108. return builder.format( `( ${ a } > ${ b } )`, type, output );
  3109. }
  3110. } else if ( op === '>=' && outputLength > 1 ) {
  3111. if ( builder.useComparisonMethod ) {
  3112. return builder.format( `${ builder.getMethod( 'greaterThanEqual', output ) }( ${ a }, ${ b } )`, type, output );
  3113. } else {
  3114. return builder.format( `( ${ a } >= ${ b } )`, type, output );
  3115. }
  3116. } else if ( op === '!' || op === '~' ) {
  3117. return builder.format( `(${op}${a})`, typeA, output );
  3118. } else if ( fnOpSnippet ) {
  3119. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3120. } else {
  3121. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3122. }
  3123. } else if ( typeA !== 'void' ) {
  3124. if ( fnOpSnippet ) {
  3125. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3126. } else {
  3127. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3128. }
  3129. }
  3130. }
  3131. serialize( data ) {
  3132. super.serialize( data );
  3133. data.op = this.op;
  3134. }
  3135. deserialize( data ) {
  3136. super.deserialize( data );
  3137. this.op = data.op;
  3138. }
  3139. }
  3140. /**
  3141. * Returns the addition of two or more value.
  3142. *
  3143. * @function
  3144. * @param {Node} aNode - The first input.
  3145. * @param {Node} bNode - The second input.
  3146. * @param {...Node} params - Additional input parameters.
  3147. * @returns {OperatorNode}
  3148. */
  3149. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' );
  3150. /**
  3151. * Returns the subtraction of two or more value.
  3152. *
  3153. * @function
  3154. * @param {Node} aNode - The first input.
  3155. * @param {Node} bNode - The second input.
  3156. * @param {...Node} params - Additional input parameters.
  3157. * @returns {OperatorNode}
  3158. */
  3159. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' );
  3160. /**
  3161. * Returns the multiplication of two or more value.
  3162. *
  3163. * @function
  3164. * @param {Node} aNode - The first input.
  3165. * @param {Node} bNode - The second input.
  3166. * @param {...Node} params - Additional input parameters.
  3167. * @returns {OperatorNode}
  3168. */
  3169. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' );
  3170. /**
  3171. * Returns the division of two or more value.
  3172. *
  3173. * @function
  3174. * @param {Node} aNode - The first input.
  3175. * @param {Node} bNode - The second input.
  3176. * @param {...Node} params - Additional input parameters.
  3177. * @returns {OperatorNode}
  3178. */
  3179. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' );
  3180. /**
  3181. * Computes the remainder of dividing the first node by the second, for integer values.
  3182. *
  3183. * @function
  3184. * @param {Node} aNode - The first input.
  3185. * @param {Node} bNode - The second input.
  3186. * @returns {OperatorNode}
  3187. */
  3188. const modInt = /*@__PURE__*/ nodeProxy( OperatorNode, '%' );
  3189. /**
  3190. * Checks if two nodes are equal.
  3191. *
  3192. * @function
  3193. * @param {Node} aNode - The first input.
  3194. * @param {Node} bNode - The second input.
  3195. * @returns {OperatorNode}
  3196. */
  3197. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' );
  3198. /**
  3199. * Checks if two nodes are not equal.
  3200. *
  3201. * @function
  3202. * @param {Node} aNode - The first input.
  3203. * @param {Node} bNode - The second input.
  3204. * @returns {OperatorNode}
  3205. */
  3206. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' );
  3207. /**
  3208. * Checks if the first node is less than the second.
  3209. *
  3210. * @function
  3211. * @param {Node} aNode - The first input.
  3212. * @param {Node} bNode - The second input.
  3213. * @returns {OperatorNode}
  3214. */
  3215. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' );
  3216. /**
  3217. * Checks if the first node is greater than the second.
  3218. *
  3219. * @function
  3220. * @param {Node} aNode - The first input.
  3221. * @param {Node} bNode - The second input.
  3222. * @returns {OperatorNode}
  3223. */
  3224. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' );
  3225. /**
  3226. * Checks if the first node is less than or equal to the second.
  3227. *
  3228. * @function
  3229. * @param {Node} aNode - The first input.
  3230. * @param {Node} bNode - The second input.
  3231. * @returns {OperatorNode}
  3232. */
  3233. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' );
  3234. /**
  3235. * Checks if the first node is greater than or equal to the second.
  3236. *
  3237. * @function
  3238. * @param {Node} aNode - The first input.
  3239. * @param {Node} bNode - The second input.
  3240. * @returns {OperatorNode}
  3241. */
  3242. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' );
  3243. /**
  3244. * Performs logical AND on two nodes.
  3245. *
  3246. * @function
  3247. * @param {Node} aNode - The first input.
  3248. * @param {Node} bNode - The second input.
  3249. * @returns {OperatorNode}
  3250. */
  3251. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' );
  3252. /**
  3253. * Performs logical OR on two nodes.
  3254. *
  3255. * @function
  3256. * @param {Node} aNode - The first input.
  3257. * @param {Node} bNode - The second input.
  3258. * @returns {OperatorNode}
  3259. */
  3260. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' );
  3261. /**
  3262. * Performs logical NOT on a node.
  3263. *
  3264. * @function
  3265. * @param {Node} aNode - The first input.
  3266. * @param {Node} bNode - The second input.
  3267. * @returns {OperatorNode}
  3268. */
  3269. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' );
  3270. /**
  3271. * Performs logical XOR on two nodes.
  3272. *
  3273. * @function
  3274. * @param {Node} aNode - The first input.
  3275. * @param {Node} bNode - The second input.
  3276. * @returns {OperatorNode}
  3277. */
  3278. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' );
  3279. /**
  3280. * Performs bitwise AND on two nodes.
  3281. *
  3282. * @function
  3283. * @param {Node} aNode - The first input.
  3284. * @param {Node} bNode - The second input.
  3285. * @returns {OperatorNode}
  3286. */
  3287. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' );
  3288. /**
  3289. * Performs bitwise NOT on a node.
  3290. *
  3291. * @function
  3292. * @param {Node} aNode - The first input.
  3293. * @param {Node} bNode - The second input.
  3294. * @returns {OperatorNode}
  3295. */
  3296. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' );
  3297. /**
  3298. * Performs bitwise OR on two nodes.
  3299. *
  3300. * @function
  3301. * @param {Node} aNode - The first input.
  3302. * @param {Node} bNode - The second input.
  3303. * @returns {OperatorNode}
  3304. */
  3305. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' );
  3306. /**
  3307. * Performs bitwise XOR on two nodes.
  3308. *
  3309. * @function
  3310. * @param {Node} aNode - The first input.
  3311. * @param {Node} bNode - The second input.
  3312. * @returns {OperatorNode}
  3313. */
  3314. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' );
  3315. /**
  3316. * Shifts a node to the left.
  3317. *
  3318. * @function
  3319. * @param {Node} aNode - The node to shift.
  3320. * @param {Node} bNode - The value to shift.
  3321. * @returns {OperatorNode}
  3322. */
  3323. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' );
  3324. /**
  3325. * Shifts a node to the right.
  3326. *
  3327. * @function
  3328. * @param {Node} aNode - The node to shift.
  3329. * @param {Node} bNode - The value to shift.
  3330. * @returns {OperatorNode}
  3331. */
  3332. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' );
  3333. addMethodChaining( 'add', add );
  3334. addMethodChaining( 'sub', sub );
  3335. addMethodChaining( 'mul', mul );
  3336. addMethodChaining( 'div', div );
  3337. addMethodChaining( 'modInt', modInt );
  3338. addMethodChaining( 'equal', equal );
  3339. addMethodChaining( 'notEqual', notEqual );
  3340. addMethodChaining( 'lessThan', lessThan );
  3341. addMethodChaining( 'greaterThan', greaterThan );
  3342. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3343. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3344. addMethodChaining( 'and', and );
  3345. addMethodChaining( 'or', or );
  3346. addMethodChaining( 'not', not );
  3347. addMethodChaining( 'xor', xor );
  3348. addMethodChaining( 'bitAnd', bitAnd );
  3349. addMethodChaining( 'bitNot', bitNot );
  3350. addMethodChaining( 'bitOr', bitOr );
  3351. addMethodChaining( 'bitXor', bitXor );
  3352. addMethodChaining( 'shiftLeft', shiftLeft );
  3353. addMethodChaining( 'shiftRight', shiftRight );
  3354. /**
  3355. * @function
  3356. * @deprecated since r168. Use {@link modInt} instead.
  3357. *
  3358. * @param {...any} params
  3359. * @returns {Function}
  3360. */
  3361. const remainder = ( ...params ) => { // @deprecated, r168
  3362. console.warn( 'TSL.OperatorNode: .remainder() has been renamed to .modInt().' );
  3363. return modInt( ...params );
  3364. };
  3365. addMethodChaining( 'remainder', remainder );
  3366. /** @module MathNode **/
  3367. /**
  3368. * This node represents a variety of mathematical methods available in shaders.
  3369. * They are divided into three categories:
  3370. *
  3371. * - Methods with one input like `sin`, `cos` or `normalize`.
  3372. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3373. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3374. *
  3375. * @augments TempNode
  3376. */
  3377. class MathNode extends TempNode {
  3378. static get type() {
  3379. return 'MathNode';
  3380. }
  3381. /**
  3382. * Constructs a new math node.
  3383. *
  3384. * @param {String} method - The method name.
  3385. * @param {Node} aNode - The first input.
  3386. * @param {Node?} [bNode=null] - The second input.
  3387. * @param {Node?} [cNode=null] - The third input.
  3388. */
  3389. constructor( method, aNode, bNode = null, cNode = null ) {
  3390. super();
  3391. /**
  3392. * The method name.
  3393. *
  3394. * @type {String}
  3395. */
  3396. this.method = method;
  3397. /**
  3398. * The first input.
  3399. *
  3400. * @type {Node}
  3401. */
  3402. this.aNode = aNode;
  3403. /**
  3404. * The second input.
  3405. *
  3406. * @type {Node?}
  3407. * @default null
  3408. */
  3409. this.bNode = bNode;
  3410. /**
  3411. * The third input.
  3412. *
  3413. * @type {Node?}
  3414. * @default null
  3415. */
  3416. this.cNode = cNode;
  3417. /**
  3418. * This flag can be used for type testing.
  3419. *
  3420. * @type {Boolean}
  3421. * @readonly
  3422. * @default true
  3423. */
  3424. this.isMathNode = true;
  3425. }
  3426. /**
  3427. * The input type is inferred from the node types of the input nodes.
  3428. *
  3429. * @param {NodeBuilder} builder - The current node builder.
  3430. * @return {String} The input type.
  3431. */
  3432. getInputType( builder ) {
  3433. const aType = this.aNode.getNodeType( builder );
  3434. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  3435. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  3436. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  3437. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  3438. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  3439. if ( aLen > bLen && aLen > cLen ) {
  3440. return aType;
  3441. } else if ( bLen > cLen ) {
  3442. return bType;
  3443. } else if ( cLen > aLen ) {
  3444. return cType;
  3445. }
  3446. return aType;
  3447. }
  3448. /**
  3449. * The selected method as well as the input type determine the node type of this node.
  3450. *
  3451. * @param {NodeBuilder} builder - The current node builder.
  3452. * @return {String} The node type.
  3453. */
  3454. getNodeType( builder ) {
  3455. const method = this.method;
  3456. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  3457. return 'float';
  3458. } else if ( method === MathNode.CROSS ) {
  3459. return 'vec3';
  3460. } else if ( method === MathNode.ALL ) {
  3461. return 'bool';
  3462. } else if ( method === MathNode.EQUALS ) {
  3463. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  3464. } else if ( method === MathNode.MOD ) {
  3465. return this.aNode.getNodeType( builder );
  3466. } else {
  3467. return this.getInputType( builder );
  3468. }
  3469. }
  3470. generate( builder, output ) {
  3471. let method = this.method;
  3472. const type = this.getNodeType( builder );
  3473. const inputType = this.getInputType( builder );
  3474. const a = this.aNode;
  3475. const b = this.bNode;
  3476. const c = this.cNode;
  3477. const coordinateSystem = builder.renderer.coordinateSystem;
  3478. if ( method === MathNode.TRANSFORM_DIRECTION ) {
  3479. // dir can be either a direction vector or a normal vector
  3480. // upper-left 3x3 of matrix is assumed to be orthogonal
  3481. let tA = a;
  3482. let tB = b;
  3483. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  3484. tB = vec4( vec3( tB ), 0.0 );
  3485. } else {
  3486. tA = vec4( vec3( tA ), 0.0 );
  3487. }
  3488. const mulNode = mul( tA, tB ).xyz;
  3489. return normalize( mulNode ).build( builder, output );
  3490. } else if ( method === MathNode.NEGATE ) {
  3491. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  3492. } else if ( method === MathNode.ONE_MINUS ) {
  3493. return sub( 1.0, a ).build( builder, output );
  3494. } else if ( method === MathNode.RECIPROCAL ) {
  3495. return div( 1.0, a ).build( builder, output );
  3496. } else if ( method === MathNode.DIFFERENCE ) {
  3497. return abs( sub( a, b ) ).build( builder, output );
  3498. } else {
  3499. const params = [];
  3500. if ( method === MathNode.CROSS || method === MathNode.MOD ) {
  3501. params.push(
  3502. a.build( builder, type ),
  3503. b.build( builder, type )
  3504. );
  3505. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  3506. params.push(
  3507. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  3508. b.build( builder, inputType )
  3509. );
  3510. } else if ( ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) || method === MathNode.MOD ) {
  3511. params.push(
  3512. a.build( builder, inputType ),
  3513. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3514. );
  3515. } else if ( method === MathNode.REFRACT ) {
  3516. params.push(
  3517. a.build( builder, inputType ),
  3518. b.build( builder, inputType ),
  3519. c.build( builder, 'float' )
  3520. );
  3521. } else if ( method === MathNode.MIX ) {
  3522. params.push(
  3523. a.build( builder, inputType ),
  3524. b.build( builder, inputType ),
  3525. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  3526. );
  3527. } else {
  3528. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  3529. method = 'atan2';
  3530. }
  3531. params.push( a.build( builder, inputType ) );
  3532. if ( b !== null ) params.push( b.build( builder, inputType ) );
  3533. if ( c !== null ) params.push( c.build( builder, inputType ) );
  3534. }
  3535. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  3536. }
  3537. }
  3538. serialize( data ) {
  3539. super.serialize( data );
  3540. data.method = this.method;
  3541. }
  3542. deserialize( data ) {
  3543. super.deserialize( data );
  3544. this.method = data.method;
  3545. }
  3546. }
  3547. // 1 input
  3548. MathNode.ALL = 'all';
  3549. MathNode.ANY = 'any';
  3550. MathNode.RADIANS = 'radians';
  3551. MathNode.DEGREES = 'degrees';
  3552. MathNode.EXP = 'exp';
  3553. MathNode.EXP2 = 'exp2';
  3554. MathNode.LOG = 'log';
  3555. MathNode.LOG2 = 'log2';
  3556. MathNode.SQRT = 'sqrt';
  3557. MathNode.INVERSE_SQRT = 'inversesqrt';
  3558. MathNode.FLOOR = 'floor';
  3559. MathNode.CEIL = 'ceil';
  3560. MathNode.NORMALIZE = 'normalize';
  3561. MathNode.FRACT = 'fract';
  3562. MathNode.SIN = 'sin';
  3563. MathNode.COS = 'cos';
  3564. MathNode.TAN = 'tan';
  3565. MathNode.ASIN = 'asin';
  3566. MathNode.ACOS = 'acos';
  3567. MathNode.ATAN = 'atan';
  3568. MathNode.ABS = 'abs';
  3569. MathNode.SIGN = 'sign';
  3570. MathNode.LENGTH = 'length';
  3571. MathNode.NEGATE = 'negate';
  3572. MathNode.ONE_MINUS = 'oneMinus';
  3573. MathNode.DFDX = 'dFdx';
  3574. MathNode.DFDY = 'dFdy';
  3575. MathNode.ROUND = 'round';
  3576. MathNode.RECIPROCAL = 'reciprocal';
  3577. MathNode.TRUNC = 'trunc';
  3578. MathNode.FWIDTH = 'fwidth';
  3579. MathNode.TRANSPOSE = 'transpose';
  3580. // 2 inputs
  3581. MathNode.BITCAST = 'bitcast';
  3582. MathNode.EQUALS = 'equals';
  3583. MathNode.MIN = 'min';
  3584. MathNode.MAX = 'max';
  3585. MathNode.MOD = 'mod';
  3586. MathNode.STEP = 'step';
  3587. MathNode.REFLECT = 'reflect';
  3588. MathNode.DISTANCE = 'distance';
  3589. MathNode.DIFFERENCE = 'difference';
  3590. MathNode.DOT = 'dot';
  3591. MathNode.CROSS = 'cross';
  3592. MathNode.POW = 'pow';
  3593. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  3594. // 3 inputs
  3595. MathNode.MIX = 'mix';
  3596. MathNode.CLAMP = 'clamp';
  3597. MathNode.REFRACT = 'refract';
  3598. MathNode.SMOOTHSTEP = 'smoothstep';
  3599. MathNode.FACEFORWARD = 'faceforward';
  3600. // 1 inputs
  3601. /**
  3602. * A small value used to handle floating-point precision errors.
  3603. *
  3604. * @type {Node<float>}
  3605. */
  3606. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  3607. /**
  3608. * Represents infinity.
  3609. *
  3610. * @type {Node<float>}
  3611. */
  3612. const INFINITY = /*@__PURE__*/ float( 1e6 );
  3613. /**
  3614. * Represents PI.
  3615. *
  3616. * @type {Node<float>}
  3617. */
  3618. const PI = /*@__PURE__*/ float( Math.PI );
  3619. /**
  3620. * Represents PI * 2.
  3621. *
  3622. * @type {Node<float>}
  3623. */
  3624. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  3625. /**
  3626. * Returns `true` if all components of `x` are `true`.
  3627. *
  3628. * @function
  3629. * @param {Node | Number} x - The parameter.
  3630. * @returns {Node<bool>}
  3631. */
  3632. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL );
  3633. /**
  3634. * Returns `true` if any components of `x` are `true`.
  3635. *
  3636. * @function
  3637. * @param {Node | Number} x - The parameter.
  3638. * @returns {Node<bool>}
  3639. */
  3640. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY );
  3641. /**
  3642. * Converts a quantity in degrees to radians.
  3643. *
  3644. * @function
  3645. * @param {Node | Number} x - The input in degrees.
  3646. * @returns {Node}
  3647. */
  3648. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS );
  3649. /**
  3650. * Convert a quantity in radians to degrees.
  3651. *
  3652. * @function
  3653. * @param {Node | Number} x - The input in radians.
  3654. * @returns {Node}
  3655. */
  3656. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES );
  3657. /**
  3658. * Returns the natural exponentiation of the parameter.
  3659. *
  3660. * @function
  3661. * @param {Node | Number} x - The parameter.
  3662. * @returns {Node}
  3663. */
  3664. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP );
  3665. /**
  3666. * Returns 2 raised to the power of the parameter.
  3667. *
  3668. * @function
  3669. * @param {Node | Number} x - The parameter.
  3670. * @returns {Node}
  3671. */
  3672. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 );
  3673. /**
  3674. * Returns the natural logarithm of the parameter.
  3675. *
  3676. * @function
  3677. * @param {Node | Number} x - The parameter.
  3678. * @returns {Node}
  3679. */
  3680. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG );
  3681. /**
  3682. * Returns the base 2 logarithm of the parameter.
  3683. *
  3684. * @function
  3685. * @param {Node | Number} x - The parameter.
  3686. * @returns {Node}
  3687. */
  3688. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 );
  3689. /**
  3690. * Returns the square root of the parameter.
  3691. *
  3692. * @function
  3693. * @param {Node | Number} x - The parameter.
  3694. * @returns {Node}
  3695. */
  3696. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT );
  3697. /**
  3698. * Returns the inverse of the square root of the parameter.
  3699. *
  3700. * @function
  3701. * @param {Node | Number} x - The parameter.
  3702. * @returns {Node}
  3703. */
  3704. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT );
  3705. /**
  3706. * Finds the nearest integer less than or equal to the parameter.
  3707. *
  3708. * @function
  3709. * @param {Node | Number} x - The parameter.
  3710. * @returns {Node}
  3711. */
  3712. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR );
  3713. /**
  3714. * Finds the nearest integer that is greater than or equal to the parameter.
  3715. *
  3716. * @function
  3717. * @param {Node | Number} x - The parameter.
  3718. * @returns {Node}
  3719. */
  3720. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL );
  3721. /**
  3722. * Calculates the unit vector in the same direction as the original vector.
  3723. *
  3724. * @function
  3725. * @param {Node} x - The input vector.
  3726. * @returns {Node}
  3727. */
  3728. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE );
  3729. /**
  3730. * Computes the fractional part of the parameter.
  3731. *
  3732. * @function
  3733. * @param {Node | Number} x - The parameter.
  3734. * @returns {Node}
  3735. */
  3736. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT );
  3737. /**
  3738. * Returns the sine of the parameter.
  3739. *
  3740. * @function
  3741. * @param {Node | Number} x - The parameter.
  3742. * @returns {Node}
  3743. */
  3744. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN );
  3745. /**
  3746. * Returns the cosine of the parameter.
  3747. *
  3748. * @function
  3749. * @param {Node | Number} x - The parameter.
  3750. * @returns {Node}
  3751. */
  3752. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS );
  3753. /**
  3754. * Returns the tangent of the parameter.
  3755. *
  3756. * @function
  3757. * @param {Node | Number} x - The parameter.
  3758. * @returns {Node}
  3759. */
  3760. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN );
  3761. /**
  3762. * Returns the arcsine of the parameter.
  3763. *
  3764. * @function
  3765. * @param {Node | Number} x - The parameter.
  3766. * @returns {Node}
  3767. */
  3768. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN );
  3769. /**
  3770. * Returns the arccosine of the parameter.
  3771. *
  3772. * @function
  3773. * @param {Node | Number} x - The parameter.
  3774. * @returns {Node}
  3775. */
  3776. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS );
  3777. /**
  3778. * Returns the arc-tangent of the parameter.
  3779. * If two parameters are provided, the result is `atan2(y/x)`.
  3780. *
  3781. * @function
  3782. * @param {Node | Number} y - The y parameter.
  3783. * @param {(Node | Number)?} x - The x parameter.
  3784. * @returns {Node}
  3785. */
  3786. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN );
  3787. /**
  3788. * Returns the absolute value of the parameter.
  3789. *
  3790. * @function
  3791. * @param {Node | Number} x - The parameter.
  3792. * @returns {Node}
  3793. */
  3794. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS );
  3795. /**
  3796. * Extracts the sign of the parameter.
  3797. *
  3798. * @function
  3799. * @param {Node | Number} x - The parameter.
  3800. * @returns {Node}
  3801. */
  3802. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN );
  3803. /**
  3804. * Calculates the length of a vector.
  3805. *
  3806. * @function
  3807. * @param {Node} x - The parameter.
  3808. * @returns {Node<float>}
  3809. */
  3810. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH );
  3811. /**
  3812. * Negates the value of the parameter (-x).
  3813. *
  3814. * @function
  3815. * @param {Node | Number} x - The parameter.
  3816. * @returns {Node}
  3817. */
  3818. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE );
  3819. /**
  3820. * Return `1` minus the parameter.
  3821. *
  3822. * @function
  3823. * @param {Node | Number} x - The parameter.
  3824. * @returns {Node}
  3825. */
  3826. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS );
  3827. /**
  3828. * Returns the partial derivative of the parameter with respect to x.
  3829. *
  3830. * @function
  3831. * @param {Node | Number} x - The parameter.
  3832. * @returns {Node}
  3833. */
  3834. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX );
  3835. /**
  3836. * Returns the partial derivative of the parameter with respect to y.
  3837. *
  3838. * @function
  3839. * @param {Node | Number} x - The parameter.
  3840. * @returns {Node}
  3841. */
  3842. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY );
  3843. /**
  3844. * Rounds the parameter to the nearest integer.
  3845. *
  3846. * @function
  3847. * @param {Node | Number} x - The parameter.
  3848. * @returns {Node}
  3849. */
  3850. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND );
  3851. /**
  3852. * Returns the reciprocal of the parameter `(1/x)`.
  3853. *
  3854. * @function
  3855. * @param {Node | Number} x - The parameter.
  3856. * @returns {Node}
  3857. */
  3858. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL );
  3859. /**
  3860. * Truncates the parameter, removing the fractional part.
  3861. *
  3862. * @function
  3863. * @param {Node | Number} x - The parameter.
  3864. * @returns {Node}
  3865. */
  3866. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC );
  3867. /**
  3868. * Returns the sum of the absolute derivatives in x and y.
  3869. *
  3870. * @function
  3871. * @param {Node | Number} x - The parameter.
  3872. * @returns {Node}
  3873. */
  3874. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH );
  3875. /**
  3876. * Returns the transpose of a matrix.
  3877. *
  3878. * @function
  3879. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  3880. * @returns {Node}
  3881. */
  3882. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE );
  3883. // 2 inputs
  3884. /**
  3885. * Reinterpret the bit representation of a value in one type as a value in another type.
  3886. *
  3887. * @function
  3888. * @param {Node | Number} x - The parameter.
  3889. * @param {String} y - The new type.
  3890. * @returns {Node}
  3891. */
  3892. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST );
  3893. /**
  3894. * Returns `true` if `x` equals `y`.
  3895. *
  3896. * @function
  3897. * @param {Node | Number} x - The first parameter.
  3898. * @param {Node | Number} y - The second parameter.
  3899. * @returns {Node<bool>}
  3900. */
  3901. const equals = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EQUALS );
  3902. /**
  3903. * Returns the lesser of two values.
  3904. *
  3905. * @function
  3906. * @param {Node | Number} x - The y parameter.
  3907. * @param {Node | Number} y - The x parameter.
  3908. * @returns {Node}
  3909. */
  3910. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN );
  3911. /**
  3912. * Returns the greater of two values.
  3913. *
  3914. * @function
  3915. * @param {Node | Number} x - The y parameter.
  3916. * @param {Node | Number} y - The x parameter.
  3917. * @returns {Node}
  3918. */
  3919. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX );
  3920. /**
  3921. * Computes the remainder of dividing the first node by the second one.
  3922. *
  3923. * @function
  3924. * @param {Node | Number} x - The y parameter.
  3925. * @param {Node | Number} y - The x parameter.
  3926. * @returns {Node}
  3927. */
  3928. const mod = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MOD );
  3929. /**
  3930. * Generate a step function by comparing two values.
  3931. *
  3932. * @function
  3933. * @param {Node | Number} x - The y parameter.
  3934. * @param {Node | Number} y - The x parameter.
  3935. * @returns {Node}
  3936. */
  3937. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP );
  3938. /**
  3939. * Calculates the reflection direction for an incident vector.
  3940. *
  3941. * @function
  3942. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  3943. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  3944. * @returns {Node<vec2|vec3|vec4>}
  3945. */
  3946. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT );
  3947. /**
  3948. * Calculates the distance between two points.
  3949. *
  3950. * @function
  3951. * @param {Node<vec2|vec3|vec4>} x - The first point.
  3952. * @param {Node<vec2|vec3|vec4>} y - The second point.
  3953. * @returns {Node<float>}
  3954. */
  3955. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE );
  3956. /**
  3957. * Calculates the absolute difference between two values.
  3958. *
  3959. * @function
  3960. * @param {Node | Number} x - The first parameter.
  3961. * @param {Node | Number} y - The second parameter.
  3962. * @returns {Node}
  3963. */
  3964. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE );
  3965. /**
  3966. * Calculates the dot product of two vectors.
  3967. *
  3968. * @function
  3969. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3970. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3971. * @returns {Node<float>}
  3972. */
  3973. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT );
  3974. /**
  3975. * Calculates the cross product of two vectors.
  3976. *
  3977. * @function
  3978. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  3979. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  3980. * @returns {Node<vec2|vec3|vec4>}
  3981. */
  3982. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS );
  3983. /**
  3984. * Return the value of the first parameter raised to the power of the second one.
  3985. *
  3986. * @function
  3987. * @param {Node | Number} x - The first parameter.
  3988. * @param {Node | Number} y - The second parameter.
  3989. * @returns {Node}
  3990. */
  3991. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW );
  3992. /**
  3993. * Returns the square of the parameter.
  3994. *
  3995. * @function
  3996. * @param {Node | Number} x - The first parameter.
  3997. * @returns {Node}
  3998. */
  3999. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 );
  4000. /**
  4001. * Returns the cube of the parameter.
  4002. *
  4003. * @function
  4004. * @param {Node | Number} x - The first parameter.
  4005. * @returns {Node}
  4006. */
  4007. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 );
  4008. /**
  4009. * Returns the fourth power of the parameter.
  4010. *
  4011. * @function
  4012. * @param {Node | Number} x - The first parameter.
  4013. * @returns {Node}
  4014. */
  4015. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 );
  4016. /**
  4017. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4018. *
  4019. * @function
  4020. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4021. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4022. * @returns {Node}
  4023. */
  4024. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION );
  4025. /**
  4026. * Returns the cube root of a number.
  4027. *
  4028. * @function
  4029. * @param {Node | Number} a - The first parameter.
  4030. * @returns {Node}
  4031. */
  4032. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4033. /**
  4034. * Calculate the squared length of a vector.
  4035. *
  4036. * @function
  4037. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4038. * @returns {Node<float>}
  4039. */
  4040. const lengthSq = ( a ) => dot( a, a );
  4041. /**
  4042. * Linearly interpolates between two values.
  4043. *
  4044. * @function
  4045. * @param {Node | Number} a - The first parameter.
  4046. * @param {Node | Number} b - The second parameter.
  4047. * @param {Node | Number} t - The interpolation value.
  4048. * @returns {Node}
  4049. */
  4050. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX );
  4051. /**
  4052. * Constrains a value to lie between two further values.
  4053. *
  4054. * @function
  4055. * @param {Node | Number} value - The value to constrain.
  4056. * @param {Node | Number} [low=0] - The lower bound.
  4057. * @param {Node | Number} [high=1] - The upper bound.
  4058. * @returns {Node}
  4059. */
  4060. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4061. /**
  4062. * Constrains a value between `0` and `1`.
  4063. *
  4064. * @function
  4065. * @param {Node | Number} value - The value to constrain.
  4066. * @returns {Node}
  4067. */
  4068. const saturate = ( value ) => clamp( value );
  4069. /**
  4070. * Calculates the refraction direction for an incident vector.
  4071. *
  4072. * @function
  4073. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4074. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4075. * @param {Node<float>} eta - The the ratio of indices of refraction.
  4076. * @returns {Node<vec2|vec3|vec4>}
  4077. */
  4078. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT );
  4079. /**
  4080. * Performs a Hermite interpolation between two values.
  4081. *
  4082. * @function
  4083. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4084. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4085. * @param {Node | Number} x - The source value for interpolation.
  4086. * @returns {Node}
  4087. */
  4088. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP );
  4089. /**
  4090. * Returns a vector pointing in the same direction as another.
  4091. *
  4092. * @function
  4093. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4094. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4095. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4096. * @returns {Node<vec2|vec3|vec4>}
  4097. */
  4098. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD );
  4099. /**
  4100. * Returns a random value for the given uv.
  4101. *
  4102. * @function
  4103. * @param {Node<vec2>} uv - The uv node.
  4104. * @returns {Node<float>}
  4105. */
  4106. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4107. const a = 12.9898, b = 78.233, c = 43758.5453;
  4108. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4109. return fract( sin( sn ).mul( c ) );
  4110. } );
  4111. /**
  4112. * Alias for `mix()` with a different parameter order.
  4113. *
  4114. * @function
  4115. * @param {Node | Number} t - The interpolation value.
  4116. * @param {Node | Number} e1 - The first parameter.
  4117. * @param {Node | Number} e2 - The second parameter.
  4118. * @returns {Node}
  4119. */
  4120. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4121. /**
  4122. * Alias for `smoothstep()` with a different parameter order.
  4123. *
  4124. * @function
  4125. * @param {Node | Number} x - The source value for interpolation.
  4126. * @param {Node | Number} low - The value of the lower edge of the Hermite function.
  4127. * @param {Node | Number} high - The value of the upper edge of the Hermite function.
  4128. * @returns {Node}
  4129. */
  4130. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4131. /**
  4132. * Returns the arc-tangent of the quotient of its parameters.
  4133. *
  4134. * @function
  4135. * @deprecated since r172. Use {@link atan} instead.
  4136. *
  4137. * @param {Node | Number} y - The y parameter.
  4138. * @param {Node | Number} x - The x parameter.
  4139. * @returns {Node}
  4140. */
  4141. const atan2 = ( y, x ) => { // @deprecated, r172
  4142. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4143. return atan( y, x );
  4144. };
  4145. // GLSL alias function
  4146. const faceforward = faceForward;
  4147. const inversesqrt = inverseSqrt;
  4148. // Method chaining
  4149. addMethodChaining( 'all', all );
  4150. addMethodChaining( 'any', any );
  4151. addMethodChaining( 'equals', equals );
  4152. addMethodChaining( 'radians', radians );
  4153. addMethodChaining( 'degrees', degrees );
  4154. addMethodChaining( 'exp', exp );
  4155. addMethodChaining( 'exp2', exp2 );
  4156. addMethodChaining( 'log', log );
  4157. addMethodChaining( 'log2', log2 );
  4158. addMethodChaining( 'sqrt', sqrt );
  4159. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4160. addMethodChaining( 'floor', floor );
  4161. addMethodChaining( 'ceil', ceil );
  4162. addMethodChaining( 'normalize', normalize );
  4163. addMethodChaining( 'fract', fract );
  4164. addMethodChaining( 'sin', sin );
  4165. addMethodChaining( 'cos', cos );
  4166. addMethodChaining( 'tan', tan );
  4167. addMethodChaining( 'asin', asin );
  4168. addMethodChaining( 'acos', acos );
  4169. addMethodChaining( 'atan', atan );
  4170. addMethodChaining( 'abs', abs );
  4171. addMethodChaining( 'sign', sign );
  4172. addMethodChaining( 'length', length );
  4173. addMethodChaining( 'lengthSq', lengthSq );
  4174. addMethodChaining( 'negate', negate );
  4175. addMethodChaining( 'oneMinus', oneMinus );
  4176. addMethodChaining( 'dFdx', dFdx );
  4177. addMethodChaining( 'dFdy', dFdy );
  4178. addMethodChaining( 'round', round );
  4179. addMethodChaining( 'reciprocal', reciprocal );
  4180. addMethodChaining( 'trunc', trunc );
  4181. addMethodChaining( 'fwidth', fwidth );
  4182. addMethodChaining( 'atan2', atan2 );
  4183. addMethodChaining( 'min', min$1 );
  4184. addMethodChaining( 'max', max$1 );
  4185. addMethodChaining( 'mod', mod );
  4186. addMethodChaining( 'step', step );
  4187. addMethodChaining( 'reflect', reflect );
  4188. addMethodChaining( 'distance', distance );
  4189. addMethodChaining( 'dot', dot );
  4190. addMethodChaining( 'cross', cross );
  4191. addMethodChaining( 'pow', pow );
  4192. addMethodChaining( 'pow2', pow2 );
  4193. addMethodChaining( 'pow3', pow3 );
  4194. addMethodChaining( 'pow4', pow4 );
  4195. addMethodChaining( 'transformDirection', transformDirection );
  4196. addMethodChaining( 'mix', mixElement );
  4197. addMethodChaining( 'clamp', clamp );
  4198. addMethodChaining( 'refract', refract );
  4199. addMethodChaining( 'smoothstep', smoothstepElement );
  4200. addMethodChaining( 'faceForward', faceForward );
  4201. addMethodChaining( 'difference', difference );
  4202. addMethodChaining( 'saturate', saturate );
  4203. addMethodChaining( 'cbrt', cbrt );
  4204. addMethodChaining( 'transpose', transpose );
  4205. addMethodChaining( 'rand', rand );
  4206. /** @module ConditionalNode **/
  4207. /**
  4208. * Represents a logical `if/else` statement. Can be used as an alternative
  4209. * to the `If()`/`Else()` syntax.
  4210. *
  4211. * The corresponding TSL `select()` looks like so:
  4212. * ```js
  4213. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4214. * ```
  4215. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4216. * determine the outcome of the entire statement.
  4217. *
  4218. * @augments Node
  4219. */
  4220. class ConditionalNode extends Node {
  4221. static get type() {
  4222. return 'ConditionalNode';
  4223. }
  4224. /**
  4225. * Constructs a new conditional node.
  4226. *
  4227. * @param {Node} condNode - The node that defines the condition.
  4228. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4229. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4230. */
  4231. constructor( condNode, ifNode, elseNode = null ) {
  4232. super();
  4233. /**
  4234. * The node that defines the condition.
  4235. *
  4236. * @type {Node}
  4237. */
  4238. this.condNode = condNode;
  4239. /**
  4240. * The node that is evaluate when the condition ends up `true`.
  4241. *
  4242. * @type {Node}
  4243. */
  4244. this.ifNode = ifNode;
  4245. /**
  4246. * The node that is evaluate when the condition ends up `false`.
  4247. *
  4248. * @type {Node?}
  4249. * @default null
  4250. */
  4251. this.elseNode = elseNode;
  4252. }
  4253. /**
  4254. * This method is overwritten since the node type is inferred from the if/else
  4255. * nodes.
  4256. *
  4257. * @param {NodeBuilder} builder - The current node builder.
  4258. * @return {String} The node type.
  4259. */
  4260. getNodeType( builder ) {
  4261. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4262. if ( ifNode === undefined ) {
  4263. // fallback setup
  4264. this.setup( builder );
  4265. return this.getNodeType( builder );
  4266. }
  4267. const ifType = ifNode.getNodeType( builder );
  4268. if ( elseNode !== null ) {
  4269. const elseType = elseNode.getNodeType( builder );
  4270. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4271. return elseType;
  4272. }
  4273. }
  4274. return ifType;
  4275. }
  4276. setup( builder ) {
  4277. const condNode = this.condNode.cache();
  4278. const ifNode = this.ifNode.cache();
  4279. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4280. //
  4281. const currentNodeBlock = builder.context.nodeBlock;
  4282. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4283. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4284. //
  4285. const properties = builder.getNodeProperties( this );
  4286. properties.condNode = condNode;
  4287. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4288. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4289. }
  4290. generate( builder, output ) {
  4291. const type = this.getNodeType( builder );
  4292. const nodeData = builder.getDataFromNode( this );
  4293. if ( nodeData.nodeProperty !== undefined ) {
  4294. return nodeData.nodeProperty;
  4295. }
  4296. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4297. const needsOutput = output !== 'void';
  4298. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4299. nodeData.nodeProperty = nodeProperty;
  4300. const nodeSnippet = condNode.build( builder, 'bool' );
  4301. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4302. let ifSnippet = ifNode.build( builder, type );
  4303. if ( ifSnippet ) {
  4304. if ( needsOutput ) {
  4305. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4306. } else {
  4307. ifSnippet = 'return ' + ifSnippet + ';';
  4308. }
  4309. }
  4310. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  4311. if ( elseNode !== null ) {
  4312. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  4313. let elseSnippet = elseNode.build( builder, type );
  4314. if ( elseSnippet ) {
  4315. if ( needsOutput ) {
  4316. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  4317. } else {
  4318. elseSnippet = 'return ' + elseSnippet + ';';
  4319. }
  4320. }
  4321. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  4322. } else {
  4323. builder.addFlowCode( '\n\n' );
  4324. }
  4325. return builder.format( nodeProperty, type, output );
  4326. }
  4327. }
  4328. /**
  4329. * TSL function for creating a conditional node.
  4330. *
  4331. * @function
  4332. * @param {Node} condNode - The node that defines the condition.
  4333. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4334. * @param {Node?} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4335. * @returns {ConditionalNode}
  4336. */
  4337. const select = /*@__PURE__*/ nodeProxy( ConditionalNode );
  4338. addMethodChaining( 'select', select );
  4339. // deprecated
  4340. /**
  4341. * @function
  4342. * @deprecated since r168. Use {@link select} instead.
  4343. *
  4344. * @param {...any} params
  4345. * @returns {ConditionalNode}
  4346. */
  4347. const cond = ( ...params ) => { // @deprecated, r168
  4348. console.warn( 'TSL.ConditionalNode: cond() has been renamed to select().' );
  4349. return select( ...params );
  4350. };
  4351. addMethodChaining( 'cond', cond );
  4352. /** @module ContextNode **/
  4353. /**
  4354. * This node can be used as a context management component for another node.
  4355. * {@link NodeBuilder} performs its node building process in a specific context and
  4356. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  4357. *
  4358. * ```js
  4359. *node.context( { getUV: () => customCoord } );
  4360. *```
  4361. * @augments Node
  4362. */
  4363. class ContextNode extends Node {
  4364. static get type() {
  4365. return 'ContextNode';
  4366. }
  4367. /**
  4368. * Constructs a new context node.
  4369. *
  4370. * @param {Node} node - The node whose context should be modified.
  4371. * @param {Object} [value={}] - The modified context data.
  4372. */
  4373. constructor( node, value = {} ) {
  4374. super();
  4375. /**
  4376. * This flag can be used for type testing.
  4377. *
  4378. * @type {Boolean}
  4379. * @readonly
  4380. * @default true
  4381. */
  4382. this.isContextNode = true;
  4383. /**
  4384. * The node whose context should be modified.
  4385. *
  4386. * @type {Node}
  4387. */
  4388. this.node = node;
  4389. /**
  4390. * The modified context data.
  4391. *
  4392. * @type {Object}
  4393. * @default {}
  4394. */
  4395. this.value = value;
  4396. }
  4397. /**
  4398. * This method is overwritten to ensure it returns the reference to {@link module:ContextNode~ContextNode#node}.
  4399. *
  4400. * @return {Node} A reference to {@link module:ContextNode~ContextNode#node}.
  4401. */
  4402. getScope() {
  4403. return this.node.getScope();
  4404. }
  4405. /**
  4406. * This method is overwritten to ensure it returns the type of {@link module:ContextNode~ContextNode#node}.
  4407. *
  4408. * @param {NodeBuilder} builder - The current node builder.
  4409. * @return {String} The node type.
  4410. */
  4411. getNodeType( builder ) {
  4412. return this.node.getNodeType( builder );
  4413. }
  4414. analyze( builder ) {
  4415. this.node.build( builder );
  4416. }
  4417. setup( builder ) {
  4418. const previousContext = builder.getContext();
  4419. builder.setContext( { ...builder.context, ...this.value } );
  4420. const node = this.node.build( builder );
  4421. builder.setContext( previousContext );
  4422. return node;
  4423. }
  4424. generate( builder, output ) {
  4425. const previousContext = builder.getContext();
  4426. builder.setContext( { ...builder.context, ...this.value } );
  4427. const snippet = this.node.build( builder, output );
  4428. builder.setContext( previousContext );
  4429. return snippet;
  4430. }
  4431. }
  4432. /**
  4433. * TSL function for creating a context node.
  4434. *
  4435. * @function
  4436. * @param {Node} node - The node whose context should be modified.
  4437. * @param {Object} [value={}] - The modified context data.
  4438. * @returns {ContextNode}
  4439. */
  4440. const context = /*@__PURE__*/ nodeProxy( ContextNode );
  4441. /**
  4442. * TSL function for defining a label context value for a given node.
  4443. *
  4444. * @function
  4445. * @param {Node} node - The node whose context should be modified.
  4446. * @param {String} name - The name/label to set.
  4447. * @returns {ContextNode}
  4448. */
  4449. const label = ( node, name ) => context( node, { label: name } );
  4450. addMethodChaining( 'context', context );
  4451. addMethodChaining( 'label', label );
  4452. /** @module VarNode **/
  4453. /**
  4454. * Class for representing shader variables as nodes. Variables are created from
  4455. * existing nodes like the following:
  4456. *
  4457. * ```js
  4458. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  4459. * ```
  4460. *
  4461. * @augments Node
  4462. */
  4463. class VarNode extends Node {
  4464. static get type() {
  4465. return 'VarNode';
  4466. }
  4467. /**
  4468. * Constructs a new variable node.
  4469. *
  4470. * @param {Node} node - The node for which a variable should be created.
  4471. * @param {String?} name - The name of the variable in the shader.
  4472. * @param {Boolean?} readOnly - The read-only flag.
  4473. */
  4474. constructor( node, name = null, readOnly = false ) {
  4475. super();
  4476. /**
  4477. * The node for which a variable should be created.
  4478. *
  4479. * @type {Node}
  4480. */
  4481. this.node = node;
  4482. /**
  4483. * The name of the variable in the shader. If no name is defined,
  4484. * the node system auto-generates one.
  4485. *
  4486. * @type {String?}
  4487. * @default null
  4488. */
  4489. this.name = name;
  4490. /**
  4491. * `VarNode` sets this property to `true` by default.
  4492. *
  4493. * @type {Boolean}
  4494. * @default true
  4495. */
  4496. this.global = true;
  4497. /**
  4498. * This flag can be used for type testing.
  4499. *
  4500. * @type {Boolean}
  4501. * @readonly
  4502. * @default true
  4503. */
  4504. this.isVarNode = true;
  4505. /**
  4506. *
  4507. * The read-only flag.
  4508. *
  4509. * @type {Boolean}
  4510. * @default false
  4511. */
  4512. this.readOnly = readOnly;
  4513. }
  4514. getHash( builder ) {
  4515. return this.name || super.getHash( builder );
  4516. }
  4517. getNodeType( builder ) {
  4518. return this.node.getNodeType( builder );
  4519. }
  4520. generate( builder ) {
  4521. const { node, name, readOnly } = this;
  4522. const { renderer } = builder;
  4523. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  4524. let isDeterministic = false;
  4525. let shouldTreatAsReadOnly = false;
  4526. if ( readOnly ) {
  4527. isDeterministic = builder.isDeterministic( node );
  4528. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  4529. }
  4530. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  4531. const snippet = node.build( builder, vectorType );
  4532. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  4533. const propertyName = builder.getPropertyName( nodeVar );
  4534. let declarationPrefix = propertyName;
  4535. if ( shouldTreatAsReadOnly ) {
  4536. const type = builder.getType( nodeVar.type );
  4537. if ( isWebGPUBackend ) {
  4538. declarationPrefix = isDeterministic
  4539. ? `const ${ propertyName }`
  4540. : `let ${ propertyName }`;
  4541. } else {
  4542. declarationPrefix = `const ${ type } ${ propertyName }`;
  4543. }
  4544. }
  4545. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  4546. return propertyName;
  4547. }
  4548. }
  4549. /**
  4550. * TSL function for creating a var node.
  4551. *
  4552. * @function
  4553. * @param {Node} node - The node for which a variable should be created.
  4554. * @param {String?} name - The name of the variable in the shader.
  4555. * @returns {VarNode}
  4556. */
  4557. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  4558. /**
  4559. * TSL function for creating a var node.
  4560. *
  4561. * @function
  4562. * @param {Node} node - The node for which a variable should be created.
  4563. * @param {String?} name - The name of the variable in the shader.
  4564. * @returns {VarNode}
  4565. */
  4566. const Var = ( node, name = null ) => createVar( node, name ).append();
  4567. /**
  4568. * TSL function for creating a const node.
  4569. *
  4570. * @function
  4571. * @param {Node} node - The node for which a constant should be created.
  4572. * @param {String?} name - The name of the constant in the shader.
  4573. * @returns {VarNode}
  4574. */
  4575. const Const = ( node, name = null ) => createVar( node, name, true ).append();
  4576. // Method chaining
  4577. addMethodChaining( 'toVar', Var );
  4578. addMethodChaining( 'toConst', Const );
  4579. // Deprecated
  4580. /**
  4581. * @function
  4582. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  4583. *
  4584. * @param {Any} node
  4585. * @returns {VarNode}
  4586. */
  4587. const temp = ( node ) => { // @deprecated, r170
  4588. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  4589. return createVar( node );
  4590. };
  4591. addMethodChaining( 'temp', temp );
  4592. /** @module VaryingNode **/
  4593. /**
  4594. * Class for representing shader varyings as nodes. Varyings are create from
  4595. * existing nodes like the following:
  4596. *
  4597. * ```js
  4598. * const positionLocal = positionGeometry.varying( 'vPositionLocal' );
  4599. * ```
  4600. *
  4601. * @augments Node
  4602. */
  4603. class VaryingNode extends Node {
  4604. static get type() {
  4605. return 'VaryingNode';
  4606. }
  4607. /**
  4608. * Constructs a new varying node.
  4609. *
  4610. * @param {Node} node - The node for which a varying should be created.
  4611. * @param {String?} name - The name of the varying in the shader.
  4612. */
  4613. constructor( node, name = null ) {
  4614. super();
  4615. /**
  4616. * The node for which a varying should be created.
  4617. *
  4618. * @type {Node}
  4619. */
  4620. this.node = node;
  4621. /**
  4622. * The name of the varying in the shader. If no name is defined,
  4623. * the node system auto-generates one.
  4624. *
  4625. * @type {String?}
  4626. * @default null
  4627. */
  4628. this.name = name;
  4629. /**
  4630. * This flag can be used for type testing.
  4631. *
  4632. * @type {Boolean}
  4633. * @readonly
  4634. * @default true
  4635. */
  4636. this.isVaryingNode = true;
  4637. }
  4638. /**
  4639. * The method is overwritten so it always returns `true`.
  4640. *
  4641. * @param {NodeBuilder} builder - The current node builder.
  4642. * @return {Boolean} Whether this node is global or not.
  4643. */
  4644. isGlobal( /*builder*/ ) {
  4645. return true;
  4646. }
  4647. getHash( builder ) {
  4648. return this.name || super.getHash( builder );
  4649. }
  4650. getNodeType( builder ) {
  4651. // VaryingNode is auto type
  4652. return this.node.getNodeType( builder );
  4653. }
  4654. /**
  4655. * This method performs the setup of a varying node with the current node builder.
  4656. *
  4657. * @param {NodeBuilder} builder - The current node builder.
  4658. * @return {NodeVarying} The node varying from the node builder.
  4659. */
  4660. setupVarying( builder ) {
  4661. const properties = builder.getNodeProperties( this );
  4662. let varying = properties.varying;
  4663. if ( varying === undefined ) {
  4664. const name = this.name;
  4665. const type = this.getNodeType( builder );
  4666. properties.varying = varying = builder.getVaryingFromNode( this, name, type );
  4667. properties.node = this.node;
  4668. }
  4669. // this property can be used to check if the varying can be optimized for a variable
  4670. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  4671. return varying;
  4672. }
  4673. setup( builder ) {
  4674. this.setupVarying( builder );
  4675. }
  4676. analyze( builder ) {
  4677. this.setupVarying( builder );
  4678. return this.node.analyze( builder );
  4679. }
  4680. generate( builder ) {
  4681. const properties = builder.getNodeProperties( this );
  4682. const varying = this.setupVarying( builder );
  4683. const needsReassign = builder.shaderStage === 'fragment' && properties.reassignPosition === true && builder.context.needsPositionReassign;
  4684. if ( properties.propertyName === undefined || needsReassign ) {
  4685. const type = this.getNodeType( builder );
  4686. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  4687. // force node run in vertex stage
  4688. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  4689. properties.propertyName = propertyName;
  4690. if ( needsReassign ) {
  4691. // once reassign varying in fragment stage
  4692. properties.reassignPosition = false;
  4693. } else if ( properties.reassignPosition === undefined && builder.context.isPositionNodeInput ) {
  4694. properties.reassignPosition = true;
  4695. }
  4696. }
  4697. return builder.getPropertyName( varying );
  4698. }
  4699. }
  4700. /**
  4701. * TSL function for creating a varying node.
  4702. *
  4703. * @function
  4704. * @param {Node} node - The node for which a varying should be created.
  4705. * @param {String?} name - The name of the varying in the shader.
  4706. * @returns {VaryingNode}
  4707. */
  4708. const varying = /*@__PURE__*/ nodeProxy( VaryingNode );
  4709. /**
  4710. * Computes a node in the vertex stage.
  4711. *
  4712. * @function
  4713. * @param {Node} node - The node which should be executed in the vertex stage.
  4714. * @returns {VaryingNode}
  4715. */
  4716. const vertexStage = ( node ) => varying( node );
  4717. addMethodChaining( 'varying', varying );
  4718. addMethodChaining( 'vertexStage', vertexStage );
  4719. /** @module ColorSpaceFunctions **/
  4720. /**
  4721. * Converts the given color value from sRGB to linear-sRGB color space.
  4722. *
  4723. * @method
  4724. * @param {Node<vec3>} color - The sRGB color.
  4725. * @return {Node<vec3>} The linear-sRGB color.
  4726. */
  4727. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4728. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  4729. const b = color.mul( 0.0773993808 );
  4730. const factor = color.lessThanEqual( 0.04045 );
  4731. const rgbResult = mix( a, b, factor );
  4732. return rgbResult;
  4733. } ).setLayout( {
  4734. name: 'sRGBTransferEOTF',
  4735. type: 'vec3',
  4736. inputs: [
  4737. { name: 'color', type: 'vec3' }
  4738. ]
  4739. } );
  4740. /**
  4741. * Converts the given color value from linear-sRGB to sRGB color space.
  4742. *
  4743. * @method
  4744. * @param {Node<vec3>} color - The linear-sRGB color.
  4745. * @return {Node<vec3>} The sRGB color.
  4746. */
  4747. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  4748. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  4749. const b = color.mul( 12.92 );
  4750. const factor = color.lessThanEqual( 0.0031308 );
  4751. const rgbResult = mix( a, b, factor );
  4752. return rgbResult;
  4753. } ).setLayout( {
  4754. name: 'sRGBTransferOETF',
  4755. type: 'vec3',
  4756. inputs: [
  4757. { name: 'color', type: 'vec3' }
  4758. ]
  4759. } );
  4760. /** @module ColorSpaceNode **/
  4761. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  4762. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  4763. /**
  4764. * This node represents a color space conversion. Meaning it converts
  4765. * a color value from a source to a target color space.
  4766. *
  4767. * @augments TempNode
  4768. */
  4769. class ColorSpaceNode extends TempNode {
  4770. static get type() {
  4771. return 'ColorSpaceNode';
  4772. }
  4773. /**
  4774. * Constructs a new color space node.
  4775. *
  4776. * @param {Node} colorNode - Represents the color to convert.
  4777. * @param {String} source - The source color space.
  4778. * @param {String} target - The target color space.
  4779. */
  4780. constructor( colorNode, source, target ) {
  4781. super( 'vec4' );
  4782. /**
  4783. * Represents the color to convert.
  4784. *
  4785. * @type {Node}
  4786. */
  4787. this.colorNode = colorNode;
  4788. /**
  4789. * The source color space.
  4790. *
  4791. * @type {String}
  4792. */
  4793. this.source = source;
  4794. /**
  4795. * The target color space.
  4796. *
  4797. * @type {String}
  4798. */
  4799. this.target = target;
  4800. }
  4801. /**
  4802. * This method resolves the constants `WORKING_COLOR_SPACE` and
  4803. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  4804. * color management and renderer.
  4805. *
  4806. * @param {NodeBuilder} builder - The current node builder.
  4807. * @param {String} colorSpace - The color space to resolve.
  4808. * @return {String} The resolved color space.
  4809. */
  4810. resolveColorSpace( builder, colorSpace ) {
  4811. if ( colorSpace === WORKING_COLOR_SPACE ) {
  4812. return ColorManagement.workingColorSpace;
  4813. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  4814. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  4815. }
  4816. return colorSpace;
  4817. }
  4818. setup( builder ) {
  4819. const { colorNode } = this;
  4820. const source = this.resolveColorSpace( builder, this.source );
  4821. const target = this.resolveColorSpace( builder, this.target );
  4822. let outputNode = colorNode;
  4823. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  4824. return outputNode;
  4825. }
  4826. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  4827. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  4828. }
  4829. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  4830. outputNode = vec4(
  4831. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  4832. outputNode.a
  4833. );
  4834. }
  4835. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  4836. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  4837. }
  4838. return outputNode;
  4839. }
  4840. }
  4841. /**
  4842. * TSL function for converting a given color node to the current output color space.
  4843. *
  4844. * @function
  4845. * @param {Node} node - Represents the node to convert.
  4846. * @returns {ColorSpaceNode}
  4847. */
  4848. const toOutputColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, OUTPUT_COLOR_SPACE ) );
  4849. /**
  4850. * TSL function for converting a given color node to the current working color space.
  4851. *
  4852. * @function
  4853. * @param {Node} node - Represents the node to convert.
  4854. * @returns {ColorSpaceNode}
  4855. */
  4856. const toWorkingColorSpace = ( node ) => nodeObject( new ColorSpaceNode( nodeObject( node ), OUTPUT_COLOR_SPACE, WORKING_COLOR_SPACE ) );
  4857. /**
  4858. * TSL function for converting a given color node from the current working color space to the given color space.
  4859. *
  4860. * @function
  4861. * @param {Node} node - Represents the node to convert.
  4862. * @param {String} colorSpace - The target color space.
  4863. * @returns {ColorSpaceNode}
  4864. */
  4865. const workingToColorSpace = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, colorSpace ) );
  4866. /**
  4867. * TSL function for converting a given color node from the given color space to the current working color space.
  4868. *
  4869. * @function
  4870. * @param {Node} node - Represents the node to convert.
  4871. * @param {String} colorSpace - The source color space.
  4872. * @returns {ColorSpaceNode}
  4873. */
  4874. const colorSpaceToWorking = ( node, colorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), colorSpace, WORKING_COLOR_SPACE ) );
  4875. /**
  4876. * TSL function for converting a given color node from one color space to another one.
  4877. *
  4878. * @function
  4879. * @param {Node} node - Represents the node to convert.
  4880. * @param {String} sourceColorSpace - The source color space.
  4881. * @param {String} targetColorSpace - The target color space.
  4882. * @returns {ColorSpaceNode}
  4883. */
  4884. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  4885. addMethodChaining( 'toOutputColorSpace', toOutputColorSpace );
  4886. addMethodChaining( 'toWorkingColorSpace', toWorkingColorSpace );
  4887. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  4888. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  4889. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  4890. /** @module ReferenceBaseNode **/
  4891. /**
  4892. * This class is only relevant if the referenced property is array-like.
  4893. * In this case, `ReferenceElementNode` allows to refer to a specific
  4894. * element inside the data structure via an index.
  4895. *
  4896. * @augments ArrayElementNode
  4897. */
  4898. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  4899. static get type() {
  4900. return 'ReferenceElementNode';
  4901. }
  4902. /**
  4903. * Constructs a new reference element node.
  4904. *
  4905. * @param {ReferenceBaseNode?} referenceNode - The reference node.
  4906. * @param {Node} indexNode - The index node that defines the element access.
  4907. */
  4908. constructor( referenceNode, indexNode ) {
  4909. super( referenceNode, indexNode );
  4910. /**
  4911. * Similar to {@link module:ReferenceBaseNode~ReferenceBaseNode#reference}, an additional
  4912. * property references to the current node.
  4913. *
  4914. * @type {ReferenceBaseNode?}
  4915. * @default null
  4916. */
  4917. this.referenceNode = referenceNode;
  4918. /**
  4919. * This flag can be used for type testing.
  4920. *
  4921. * @type {Boolean}
  4922. * @readonly
  4923. * @default true
  4924. */
  4925. this.isReferenceElementNode = true;
  4926. }
  4927. /**
  4928. * This method is overwritten since the node type is inferred from
  4929. * the uniform type of the reference node.
  4930. *
  4931. * @return {String} The node type.
  4932. */
  4933. getNodeType() {
  4934. return this.referenceNode.uniformType;
  4935. }
  4936. generate( builder ) {
  4937. const snippet = super.generate( builder );
  4938. const arrayType = this.referenceNode.getNodeType();
  4939. const elementType = this.getNodeType();
  4940. return builder.format( snippet, arrayType, elementType );
  4941. }
  4942. };
  4943. /**
  4944. * Base class for nodes which establishes a reference to a property of another object.
  4945. * In this way, the value of the node is automatically linked to the value of
  4946. * referenced object. Reference nodes internally represent the linked value
  4947. * as a uniform.
  4948. *
  4949. * @augments Node
  4950. */
  4951. class ReferenceBaseNode extends Node {
  4952. static get type() {
  4953. return 'ReferenceBaseNode';
  4954. }
  4955. /**
  4956. * Constructs a new reference base node.
  4957. *
  4958. * @param {String} property - The name of the property the node refers to.
  4959. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  4960. * @param {Object?} [object=null] - The object the property belongs to.
  4961. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  4962. */
  4963. constructor( property, uniformType, object = null, count = null ) {
  4964. super();
  4965. /**
  4966. * The name of the property the node refers to.
  4967. *
  4968. * @type {String}
  4969. */
  4970. this.property = property;
  4971. /**
  4972. * The uniform type that should be used to represent the property value.
  4973. *
  4974. * @type {String}
  4975. */
  4976. this.uniformType = uniformType;
  4977. /**
  4978. * The object the property belongs to.
  4979. *
  4980. * @type {Object?}
  4981. * @default null
  4982. */
  4983. this.object = object;
  4984. /**
  4985. * When the linked property is an array, this parameter defines its length.
  4986. *
  4987. * @type {Number?}
  4988. * @default null
  4989. */
  4990. this.count = count;
  4991. /**
  4992. * The property name might have dots so nested properties can be referred.
  4993. * The hierarchy of the names is stored inside this array.
  4994. *
  4995. * @type {Array<String>}
  4996. */
  4997. this.properties = property.split( '.' );
  4998. /**
  4999. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  5000. * since the final reference might be updated from calling code.
  5001. *
  5002. * @type {Object?}
  5003. * @default null
  5004. */
  5005. this.reference = object;
  5006. /**
  5007. * The uniform node that holds the value of the reference node.
  5008. *
  5009. * @type {UniformNode}
  5010. * @default null
  5011. */
  5012. this.node = null;
  5013. /**
  5014. * The uniform group of the internal uniform.
  5015. *
  5016. * @type {UniformGroupNode}
  5017. * @default null
  5018. */
  5019. this.group = null;
  5020. /**
  5021. * Overwritten since reference nodes are updated per object.
  5022. *
  5023. * @type {String}
  5024. * @default 'object'
  5025. */
  5026. this.updateType = NodeUpdateType.OBJECT;
  5027. }
  5028. /**
  5029. * Sets the uniform group for this reference node.
  5030. *
  5031. * @param {UniformGroupNode} group - The uniform group to set.
  5032. * @return {ReferenceBaseNode} A reference to this node.
  5033. */
  5034. setGroup( group ) {
  5035. this.group = group;
  5036. return this;
  5037. }
  5038. /**
  5039. * When the referred property is array-like, this method can be used
  5040. * to access elements via an index node.
  5041. *
  5042. * @param {IndexNode} indexNode - indexNode.
  5043. * @return {ReferenceElementNode} A reference to an element.
  5044. */
  5045. element( indexNode ) {
  5046. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5047. }
  5048. /**
  5049. * Sets the node type which automatically defines the internal
  5050. * uniform type.
  5051. *
  5052. * @param {String} uniformType - The type to set.
  5053. */
  5054. setNodeType( uniformType ) {
  5055. const node = uniform( null, uniformType ).getSelf();
  5056. if ( this.group !== null ) {
  5057. node.setGroup( this.group );
  5058. }
  5059. this.node = node;
  5060. }
  5061. /**
  5062. * This method is overwritten since the node type is inferred from
  5063. * the type of the reference node.
  5064. *
  5065. * @param {NodeBuilder} builder - The current node builder.
  5066. * @return {String} The node type.
  5067. */
  5068. getNodeType( builder ) {
  5069. if ( this.node === null ) {
  5070. this.updateReference( builder );
  5071. this.updateValue();
  5072. }
  5073. return this.node.getNodeType( builder );
  5074. }
  5075. /**
  5076. * Returns the property value from the given referred object.
  5077. *
  5078. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5079. * @return {Any} The value.
  5080. */
  5081. getValueFromReference( object = this.reference ) {
  5082. const { properties } = this;
  5083. let value = object[ properties[ 0 ] ];
  5084. for ( let i = 1; i < properties.length; i ++ ) {
  5085. value = value[ properties[ i ] ];
  5086. }
  5087. return value;
  5088. }
  5089. /**
  5090. * Allows to update the reference based on the given state. The state is only
  5091. * evaluated {@link module:ReferenceBaseNode~ReferenceBaseNode#object} is not set.
  5092. *
  5093. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5094. * @return {Object} The updated reference.
  5095. */
  5096. updateReference( state ) {
  5097. this.reference = this.object !== null ? this.object : state.object;
  5098. return this.reference;
  5099. }
  5100. /**
  5101. * The output of the reference node is the internal uniform node.
  5102. *
  5103. * @return {UniformNode} The output node.
  5104. */
  5105. setup() {
  5106. this.updateValue();
  5107. return this.node;
  5108. }
  5109. /**
  5110. * Overwritten to to update the internal uniform value.
  5111. *
  5112. * @param {NodeFrame} frame - A reference to the current node frame.
  5113. */
  5114. update( /*frame*/ ) {
  5115. this.updateValue();
  5116. }
  5117. /**
  5118. * Retrieves the value from the referred object property and uses it
  5119. * to updated the internal uniform.
  5120. */
  5121. updateValue() {
  5122. if ( this.node === null ) this.setNodeType( this.uniformType );
  5123. const value = this.getValueFromReference();
  5124. if ( Array.isArray( value ) ) {
  5125. this.node.array = value;
  5126. } else {
  5127. this.node.value = value;
  5128. }
  5129. }
  5130. }
  5131. /**
  5132. * TSL function for creating a reference base node.
  5133. *
  5134. * @function
  5135. * @param {String} name - The name of the property the node refers to.
  5136. * @param {String} type - The uniform type that should be used to represent the property value.
  5137. * @param {Object} object - The object the property belongs to.
  5138. * @returns {ReferenceBaseNode}
  5139. */
  5140. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5141. /** @module RendererReferenceNode **/
  5142. /**
  5143. * This node is a special type of reference node which is intended
  5144. * for linking renderer properties with node values.
  5145. * ```js
  5146. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5147. * ```
  5148. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5149. * automatically be updated.
  5150. *
  5151. * @augments ReferenceBaseNode
  5152. */
  5153. class RendererReferenceNode extends ReferenceBaseNode {
  5154. static get type() {
  5155. return 'RendererReferenceNode';
  5156. }
  5157. /**
  5158. * Constructs a new renderer reference node.
  5159. *
  5160. * @param {String} property - The name of the property the node refers to.
  5161. * @param {String} inputType - The uniform type that should be used to represent the property value.
  5162. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5163. * the node refers to the renderer of the current state.
  5164. */
  5165. constructor( property, inputType, renderer = null ) {
  5166. super( property, inputType, renderer );
  5167. /**
  5168. * The renderer the property belongs to. When no renderer is set,
  5169. * the node refers to the renderer of the current state.
  5170. *
  5171. * @type {Renderer?}
  5172. * @default null
  5173. */
  5174. this.renderer = renderer;
  5175. this.setGroup( renderGroup );
  5176. }
  5177. /**
  5178. * Updates the reference based on the given state. The state is only evaluated
  5179. * {@link module:RendererReferenceNode~RendererReferenceNode#renderer} is not set.
  5180. *
  5181. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5182. * @return {Object} The updated reference.
  5183. */
  5184. updateReference( state ) {
  5185. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5186. return this.reference;
  5187. }
  5188. }
  5189. /**
  5190. * TSL function for creating a renderer reference node.
  5191. *
  5192. * @function
  5193. * @param {String} name - The name of the property the node refers to.
  5194. * @param {String} type - The uniform type that should be used to represent the property value.
  5195. * @param {Renderer?} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5196. * the node refers to the renderer of the current state.
  5197. * @returns {RendererReferenceNode}
  5198. */
  5199. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5200. /** @module ToneMappingNode **/
  5201. /**
  5202. * This node represents a tone mapping operation.
  5203. *
  5204. * @augments TempNode
  5205. */
  5206. class ToneMappingNode extends TempNode {
  5207. static get type() {
  5208. return 'ToneMappingNode';
  5209. }
  5210. /**
  5211. * Constructs a new tone mapping node.
  5212. *
  5213. * @param {Number} toneMapping - The tone mapping type.
  5214. * @param {Node} exposureNode - The tone mapping exposure.
  5215. * @param {Node} [colorNode=null] - The color node to process.
  5216. */
  5217. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5218. super( 'vec3' );
  5219. /**
  5220. * The tone mapping type.
  5221. *
  5222. * @type {Number}
  5223. */
  5224. this.toneMapping = toneMapping;
  5225. /**
  5226. * The tone mapping exposure.
  5227. *
  5228. * @type {Node}
  5229. * @default null
  5230. */
  5231. this.exposureNode = exposureNode;
  5232. /**
  5233. * Represents the color to process.
  5234. *
  5235. * @type {Node?}
  5236. * @default null
  5237. */
  5238. this.colorNode = colorNode;
  5239. }
  5240. /**
  5241. * Overwrites the default `customCacheKey()` implementation by including the tone
  5242. * mapping type into the cache key.
  5243. *
  5244. * @return {Number} The hash.
  5245. */
  5246. customCacheKey() {
  5247. return hash$1( this.toneMapping );
  5248. }
  5249. setup( builder ) {
  5250. const colorNode = this.colorNode || builder.context.color;
  5251. const toneMapping = this.toneMapping;
  5252. if ( toneMapping === NoToneMapping ) return colorNode;
  5253. let outputNode = null;
  5254. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5255. if ( toneMappingFn !== null ) {
  5256. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5257. } else {
  5258. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5259. outputNode = colorNode;
  5260. }
  5261. return outputNode;
  5262. }
  5263. }
  5264. /**
  5265. * TSL function for creating a tone mapping node.
  5266. *
  5267. * @function
  5268. * @param {Number} mapping - The tone mapping type.
  5269. * @param {Node<float> | Number} exposure - The tone mapping exposure.
  5270. * @param {Node<vec3> | Color} color - The color node to process.
  5271. * @returns {ToneMappingNode<vec3>}
  5272. */
  5273. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  5274. /**
  5275. * TSL object that represents the global tone mapping exposure of the renderer.
  5276. *
  5277. * @type {RendererReferenceNode<vec3>}
  5278. */
  5279. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  5280. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  5281. /** @module BufferAttributeNode **/
  5282. /**
  5283. * In earlier `three.js` versions it was only possible to define attribute data
  5284. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  5285. * on the node level.
  5286. * ```js
  5287. * const geometry = new THREE.PlaneGeometry();
  5288. * const positionAttribute = geometry.getAttribute( 'position' );
  5289. *
  5290. * const colors = [];
  5291. * for ( let i = 0; i < position.count; i ++ ) {
  5292. * colors.push( 1, 0, 0 );
  5293. * }
  5294. *
  5295. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  5296. * ```
  5297. * This new approach is especially interesting when geometry data are generated via
  5298. * compute shaders. The below line converts a storage buffer into an attribute node.
  5299. * ```js
  5300. * material.positionNode = positionBuffer.toAttribute();
  5301. * ```
  5302. * @augments InputNode
  5303. */
  5304. class BufferAttributeNode extends InputNode {
  5305. static get type() {
  5306. return 'BufferAttributeNode';
  5307. }
  5308. /**
  5309. * Constructs a new buffer attribute node.
  5310. *
  5311. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  5312. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  5313. * @param {Number} [bufferStride=0] - The buffer stride.
  5314. * @param {Number} [bufferOffset=0] - The buffer offset.
  5315. */
  5316. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  5317. super( value, bufferType );
  5318. /**
  5319. * This flag can be used for type testing.
  5320. *
  5321. * @type {Boolean}
  5322. * @readonly
  5323. * @default true
  5324. */
  5325. this.isBufferNode = true;
  5326. /**
  5327. * The buffer type (e.g. `'vec3'`).
  5328. *
  5329. * @type {String}
  5330. * @default null
  5331. */
  5332. this.bufferType = bufferType;
  5333. /**
  5334. * The buffer stride.
  5335. *
  5336. * @type {Number}
  5337. * @default 0
  5338. */
  5339. this.bufferStride = bufferStride;
  5340. /**
  5341. * The buffer offset.
  5342. *
  5343. * @type {Number}
  5344. * @default 0
  5345. */
  5346. this.bufferOffset = bufferOffset;
  5347. /**
  5348. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  5349. * if you are planning to update the attribute data per frame.
  5350. *
  5351. * @type {Number}
  5352. * @default StaticDrawUsage
  5353. */
  5354. this.usage = StaticDrawUsage;
  5355. /**
  5356. * Whether the attribute is instanced or not.
  5357. *
  5358. * @type {Boolean}
  5359. * @default false
  5360. */
  5361. this.instanced = false;
  5362. /**
  5363. * A reference to the buffer attribute.
  5364. *
  5365. * @type {BufferAttribute?}
  5366. * @default null
  5367. */
  5368. this.attribute = null;
  5369. /**
  5370. * `BufferAttributeNode` sets this property to `true` by default.
  5371. *
  5372. * @type {Boolean}
  5373. * @default true
  5374. */
  5375. this.global = true;
  5376. if ( value && value.isBufferAttribute === true ) {
  5377. this.attribute = value;
  5378. this.usage = value.usage;
  5379. this.instanced = value.isInstancedBufferAttribute;
  5380. }
  5381. }
  5382. /**
  5383. * This method is overwritten since the attribute data might be shared
  5384. * and thus the hash should be shared as well.
  5385. *
  5386. * @param {NodeBuilder} builder - The current node builder.
  5387. * @return {String} The hash.
  5388. */
  5389. getHash( builder ) {
  5390. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  5391. let bufferData = builder.globalCache.getData( this.value );
  5392. if ( bufferData === undefined ) {
  5393. bufferData = {
  5394. node: this
  5395. };
  5396. builder.globalCache.setData( this.value, bufferData );
  5397. }
  5398. return bufferData.node.uuid;
  5399. }
  5400. return this.uuid;
  5401. }
  5402. /**
  5403. * This method is overwritten since the node type is inferred from
  5404. * the buffer attribute.
  5405. *
  5406. * @param {NodeBuilder} builder - The current node builder.
  5407. * @return {String} The node type.
  5408. */
  5409. getNodeType( builder ) {
  5410. if ( this.bufferType === null ) {
  5411. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  5412. }
  5413. return this.bufferType;
  5414. }
  5415. /**
  5416. * Depending on which value was passed to the node, `setup()` behaves
  5417. * differently. If no instance of `BufferAttribute` was passed, the method
  5418. * creates an internal attribute and configures it respectively.
  5419. *
  5420. * @param {NodeBuilder} builder - The current node builder.
  5421. */
  5422. setup( builder ) {
  5423. if ( this.attribute !== null ) return;
  5424. const type = this.getNodeType( builder );
  5425. const array = this.value;
  5426. const itemSize = builder.getTypeLength( type );
  5427. const stride = this.bufferStride || itemSize;
  5428. const offset = this.bufferOffset;
  5429. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  5430. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  5431. buffer.setUsage( this.usage );
  5432. this.attribute = bufferAttribute;
  5433. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  5434. }
  5435. /**
  5436. * Generates the code snippet of the buffer attribute node.
  5437. *
  5438. * @param {NodeBuilder} builder - The current node builder.
  5439. * @return {String} The generated code snippet.
  5440. */
  5441. generate( builder ) {
  5442. const nodeType = this.getNodeType( builder );
  5443. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  5444. const propertyName = builder.getPropertyName( nodeAttribute );
  5445. let output = null;
  5446. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  5447. this.name = propertyName;
  5448. output = propertyName;
  5449. } else {
  5450. const nodeVarying = varying( this );
  5451. output = nodeVarying.build( builder, nodeType );
  5452. }
  5453. return output;
  5454. }
  5455. /**
  5456. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  5457. *
  5458. * @param {NodeBuilder} builder - The current node builder.
  5459. * @return {String} The input type.
  5460. */
  5461. getInputType( /*builder*/ ) {
  5462. return 'bufferAttribute';
  5463. }
  5464. /**
  5465. * Sets the `usage` property to the given value.
  5466. *
  5467. * @param {Number} value - The usage to set.
  5468. * @return {BufferAttributeNode} A reference to this node.
  5469. */
  5470. setUsage( value ) {
  5471. this.usage = value;
  5472. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  5473. this.attribute.usage = value;
  5474. }
  5475. return this;
  5476. }
  5477. /**
  5478. * Sets the `instanced` property to the given value.
  5479. *
  5480. * @param {Boolean} value - The value to set.
  5481. * @return {BufferAttributeNode} A reference to this node.
  5482. */
  5483. setInstanced( value ) {
  5484. this.instanced = value;
  5485. return this;
  5486. }
  5487. }
  5488. /**
  5489. * TSL function for creating a buffer attribute node.
  5490. *
  5491. * @function
  5492. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5493. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5494. * @param {Number} [stride=0] - The buffer stride.
  5495. * @param {Number} [offset=0] - The buffer offset.
  5496. * @returns {BufferAttributeNode}
  5497. */
  5498. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  5499. /**
  5500. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  5501. * Use this function if attribute data are updated per frame.
  5502. *
  5503. * @function
  5504. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5505. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5506. * @param {Number} [stride=0] - The buffer stride.
  5507. * @param {Number} [offset=0] - The buffer offset.
  5508. * @returns {BufferAttributeNode}
  5509. */
  5510. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  5511. /**
  5512. * TSL function for creating a buffer attribute node but with enabled instancing
  5513. *
  5514. * @function
  5515. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5516. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5517. * @param {Number} [stride=0] - The buffer stride.
  5518. * @param {Number} [offset=0] - The buffer offset.
  5519. * @returns {BufferAttributeNode}
  5520. */
  5521. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  5522. /**
  5523. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  5524. *
  5525. * @function
  5526. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  5527. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  5528. * @param {Number} [stride=0] - The buffer stride.
  5529. * @param {Number} [offset=0] - The buffer offset.
  5530. * @returns {BufferAttributeNode}
  5531. */
  5532. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  5533. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  5534. /** @module ComputeNode **/
  5535. /**
  5536. * TODO
  5537. *
  5538. * @augments Node
  5539. */
  5540. class ComputeNode extends Node {
  5541. static get type() {
  5542. return 'ComputeNode';
  5543. }
  5544. /**
  5545. * Constructs a new compute node.
  5546. *
  5547. * @param {Node} computeNode - TODO
  5548. * @param {Number} count - TODO.
  5549. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5550. */
  5551. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  5552. super( 'void' );
  5553. /**
  5554. * This flag can be used for type testing.
  5555. *
  5556. * @type {Boolean}
  5557. * @readonly
  5558. * @default true
  5559. */
  5560. this.isComputeNode = true;
  5561. /**
  5562. * TODO
  5563. *
  5564. * @type {Node}
  5565. */
  5566. this.computeNode = computeNode;
  5567. /**
  5568. * TODO
  5569. *
  5570. * @type {Number}
  5571. */
  5572. this.count = count;
  5573. /**
  5574. * TODO
  5575. *
  5576. * @type {Array<Number>}
  5577. * @default [64]
  5578. */
  5579. this.workgroupSize = workgroupSize;
  5580. /**
  5581. * TODO
  5582. *
  5583. * @type {Number}
  5584. */
  5585. this.dispatchCount = 0;
  5586. /**
  5587. * TODO
  5588. *
  5589. * @type {Number}
  5590. */
  5591. this.version = 1;
  5592. /**
  5593. * The name or label of the uniform.
  5594. *
  5595. * @type {String}
  5596. * @default ''
  5597. */
  5598. this.name = '';
  5599. /**
  5600. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  5601. * is executed once per object by default.
  5602. *
  5603. * @type {String}
  5604. * @default 'object'
  5605. */
  5606. this.updateBeforeType = NodeUpdateType.OBJECT;
  5607. /**
  5608. * TODO
  5609. *
  5610. * @type {Function}
  5611. */
  5612. this.onInitFunction = null;
  5613. this.updateDispatchCount();
  5614. }
  5615. /**
  5616. * Executes the `dispose` event for this node.
  5617. */
  5618. dispose() {
  5619. this.dispatchEvent( { type: 'dispose' } );
  5620. }
  5621. /**
  5622. * Sets the {@link ComputeNode#name} property.
  5623. *
  5624. * @param {String} name - The name of the uniform.
  5625. * @return {ComputeNode} A reference to this node.
  5626. */
  5627. label( name ) {
  5628. this.name = name;
  5629. return this;
  5630. }
  5631. /**
  5632. * TODO
  5633. */
  5634. updateDispatchCount() {
  5635. const { count, workgroupSize } = this;
  5636. let size = workgroupSize[ 0 ];
  5637. for ( let i = 1; i < workgroupSize.length; i ++ )
  5638. size *= workgroupSize[ i ];
  5639. this.dispatchCount = Math.ceil( count / size );
  5640. }
  5641. /**
  5642. * TODO
  5643. *
  5644. * @param {Function} callback - TODO.
  5645. * @return {ComputeNode} A reference to this node.
  5646. */
  5647. onInit( callback ) {
  5648. this.onInitFunction = callback;
  5649. return this;
  5650. }
  5651. /**
  5652. * The method execute the compute for this node.
  5653. *
  5654. * @param {NodeFrame} frame - A reference to the current node frame.
  5655. */
  5656. updateBefore( { renderer } ) {
  5657. renderer.compute( this );
  5658. }
  5659. generate( builder ) {
  5660. const { shaderStage } = builder;
  5661. if ( shaderStage === 'compute' ) {
  5662. const snippet = this.computeNode.build( builder, 'void' );
  5663. if ( snippet !== '' ) {
  5664. builder.addLineFlowCode( snippet, this );
  5665. }
  5666. }
  5667. }
  5668. }
  5669. /**
  5670. * TSL function for creating a compute node.
  5671. *
  5672. * @function
  5673. * @param {Node} node - TODO
  5674. * @param {Number} count - TODO.
  5675. * @param {Array<Number>} [workgroupSize=[64]] - TODO.
  5676. * @returns {AtomicFunctionNode}
  5677. */
  5678. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  5679. addMethodChaining( 'compute', compute );
  5680. /** @module CacheNode **/
  5681. /**
  5682. * This node can be used as a cache management component for another node.
  5683. * Caching is in general used by default in {@link NodeBuilder} but this node
  5684. * allows the usage of a shared parent cache during the build process.
  5685. *
  5686. * @augments Node
  5687. */
  5688. class CacheNode extends Node {
  5689. static get type() {
  5690. return 'CacheNode';
  5691. }
  5692. /**
  5693. * Constructs a new cache node.
  5694. *
  5695. * @param {Node} node - The node that should be cached.
  5696. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  5697. */
  5698. constructor( node, parent = true ) {
  5699. super();
  5700. /**
  5701. * The node that should be cached.
  5702. *
  5703. * @type {Node}
  5704. */
  5705. this.node = node;
  5706. /**
  5707. * Whether this node refers to a shared parent cache or not.
  5708. *
  5709. * @type {Boolean}
  5710. * @default true
  5711. */
  5712. this.parent = parent;
  5713. /**
  5714. * This flag can be used for type testing.
  5715. *
  5716. * @type {Boolean}
  5717. * @readonly
  5718. * @default true
  5719. */
  5720. this.isCacheNode = true;
  5721. }
  5722. getNodeType( builder ) {
  5723. const previousCache = builder.getCache();
  5724. const cache = builder.getCacheFromNode( this, this.parent );
  5725. builder.setCache( cache );
  5726. const nodeType = this.node.getNodeType( builder );
  5727. builder.setCache( previousCache );
  5728. return nodeType;
  5729. }
  5730. build( builder, ...params ) {
  5731. const previousCache = builder.getCache();
  5732. const cache = builder.getCacheFromNode( this, this.parent );
  5733. builder.setCache( cache );
  5734. const data = this.node.build( builder, ...params );
  5735. builder.setCache( previousCache );
  5736. return data;
  5737. }
  5738. }
  5739. /**
  5740. * TSL function for creating a cache node.
  5741. *
  5742. * @function
  5743. * @param {Node} node - The node that should be cached.
  5744. * @param {Boolean} parent - Whether this node refers to a shared parent cache or not.
  5745. * @returns {CacheNode}
  5746. */
  5747. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  5748. addMethodChaining( 'cache', cache );
  5749. /** @module BypassNode **/
  5750. /**
  5751. * The class generates the code of a given node but returns another node in the output.
  5752. * This can be used to call a method or node that does not return a value, i.e.
  5753. * type `void` on an input where returning a value is required. Example:
  5754. *
  5755. * ```js
  5756. * material.colorNode = myColor.bypass( runVoidFn() )
  5757. *```
  5758. *
  5759. * @augments Node
  5760. */
  5761. class BypassNode extends Node {
  5762. static get type() {
  5763. return 'BypassNode';
  5764. }
  5765. /**
  5766. * Constructs a new bypass node.
  5767. *
  5768. * @param {Node} outputNode - The output node.
  5769. * @param {Node} callNode - The call node.
  5770. */
  5771. constructor( outputNode, callNode ) {
  5772. super();
  5773. /**
  5774. * This flag can be used for type testing.
  5775. *
  5776. * @type {Boolean}
  5777. * @readonly
  5778. * @default true
  5779. */
  5780. this.isBypassNode = true;
  5781. /**
  5782. * The output node.
  5783. *
  5784. * @type {Node}
  5785. */
  5786. this.outputNode = outputNode;
  5787. /**
  5788. * The call node.
  5789. *
  5790. * @type {Node}
  5791. */
  5792. this.callNode = callNode;
  5793. }
  5794. getNodeType( builder ) {
  5795. return this.outputNode.getNodeType( builder );
  5796. }
  5797. generate( builder ) {
  5798. const snippet = this.callNode.build( builder, 'void' );
  5799. if ( snippet !== '' ) {
  5800. builder.addLineFlowCode( snippet, this );
  5801. }
  5802. return this.outputNode.build( builder );
  5803. }
  5804. }
  5805. /**
  5806. * TSL function for creating a bypass node.
  5807. *
  5808. * @function
  5809. * @param {Node} outputNode - The output node.
  5810. * @param {Node} callNode - The call node.
  5811. * @returns {BypassNode}
  5812. */
  5813. const bypass = /*@__PURE__*/ nodeProxy( BypassNode );
  5814. addMethodChaining( 'bypass', bypass );
  5815. /** @module RemapNode **/
  5816. /**
  5817. * This node allows to remap a node value from one range into another. E.g a value of
  5818. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  5819. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  5820. *
  5821. * @augments Node
  5822. */
  5823. class RemapNode extends Node {
  5824. static get type() {
  5825. return 'RemapNode';
  5826. }
  5827. /**
  5828. * Constructs a new remap node.
  5829. *
  5830. * @param {Node} node - The node that should be remapped.
  5831. * @param {Node} inLowNode - The source or current lower bound of the range.
  5832. * @param {Node} inHighNode - The source or current upper bound of the range.
  5833. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5834. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5835. */
  5836. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  5837. super();
  5838. /**
  5839. * The node that should be remapped.
  5840. *
  5841. * @type {Node}
  5842. */
  5843. this.node = node;
  5844. /**
  5845. * The source or current lower bound of the range.
  5846. *
  5847. * @type {Node}
  5848. */
  5849. this.inLowNode = inLowNode;
  5850. /**
  5851. * The source or current upper bound of the range.
  5852. *
  5853. * @type {Node}
  5854. */
  5855. this.inHighNode = inHighNode;
  5856. /**
  5857. * The target lower bound of the range.
  5858. *
  5859. * @type {Node}
  5860. * @default float(0)
  5861. */
  5862. this.outLowNode = outLowNode;
  5863. /**
  5864. * The target upper bound of the range.
  5865. *
  5866. * @type {Node}
  5867. * @default float(1)
  5868. */
  5869. this.outHighNode = outHighNode;
  5870. /**
  5871. * Whether the node value should be clamped before
  5872. * remapping it to the target range.
  5873. *
  5874. * @type {Boolean}
  5875. * @default true
  5876. */
  5877. this.doClamp = true;
  5878. }
  5879. setup() {
  5880. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  5881. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  5882. if ( doClamp === true ) t = t.clamp();
  5883. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  5884. }
  5885. }
  5886. /**
  5887. * TSL function for creating a remap node.
  5888. *
  5889. * @function
  5890. * @param {Node} node - The node that should be remapped.
  5891. * @param {Node} inLowNode - The source or current lower bound of the range.
  5892. * @param {Node} inHighNode - The source or current upper bound of the range.
  5893. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5894. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5895. * @returns {RemapNode}
  5896. */
  5897. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } );
  5898. /**
  5899. * TSL function for creating a remap node, but with enabled clamping.
  5900. *
  5901. * @function
  5902. * @param {Node} node - The node that should be remapped.
  5903. * @param {Node} inLowNode - The source or current lower bound of the range.
  5904. * @param {Node} inHighNode - The source or current upper bound of the range.
  5905. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  5906. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  5907. * @returns {RemapNode}
  5908. */
  5909. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode );
  5910. addMethodChaining( 'remap', remap );
  5911. addMethodChaining( 'remapClamp', remapClamp );
  5912. /** @module ExpressionNode **/
  5913. /**
  5914. * This class can be used to implement basic expressions in shader code.
  5915. * Basic examples for that are `return`, `continue` or `discard` statements.
  5916. *
  5917. * @augments Node
  5918. */
  5919. class ExpressionNode extends Node {
  5920. static get type() {
  5921. return 'ExpressionNode';
  5922. }
  5923. /**
  5924. * Constructs a new expression node.
  5925. *
  5926. * @param {String} [snippet=''] - The native code snippet.
  5927. * @param {String} [nodeType='void'] - The node type.
  5928. */
  5929. constructor( snippet = '', nodeType = 'void' ) {
  5930. super( nodeType );
  5931. /**
  5932. * The native code snippet.
  5933. *
  5934. * @type {String}
  5935. * @default ''
  5936. */
  5937. this.snippet = snippet;
  5938. }
  5939. generate( builder, output ) {
  5940. const type = this.getNodeType( builder );
  5941. const snippet = this.snippet;
  5942. if ( type === 'void' ) {
  5943. builder.addLineFlowCode( snippet, this );
  5944. } else {
  5945. return builder.format( `( ${ snippet } )`, type, output );
  5946. }
  5947. }
  5948. }
  5949. /**
  5950. * TSL function for creating an expression node.
  5951. *
  5952. * @function
  5953. * @param {String} [snippet=''] - The native code snippet.
  5954. * @param {String} [nodeType='void'] - The node type.
  5955. * @returns {ExpressionNode}
  5956. */
  5957. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode );
  5958. /** @module Discard **/
  5959. /**
  5960. * Represents a `discard` shader operation in TSL.
  5961. *
  5962. * @method
  5963. * @param {ConditionalNode?} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  5964. * @return {Node} The `discard` expression.
  5965. */
  5966. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).append();
  5967. /**
  5968. * Represents a `return` shader operation in TSL.
  5969. *
  5970. * @method
  5971. * @return {ExpressionNode} The `return` expression.
  5972. */
  5973. const Return = () => expression( 'return' ).append();
  5974. addMethodChaining( 'discard', Discard );
  5975. /** @module RenderOutputNode **/
  5976. /**
  5977. * Normally, tone mapping and color conversion happens automatically
  5978. * before outputting pixel too the default (screen) framebuffer. In certain
  5979. * post processing setups this happens to late because certain effects
  5980. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  5981. * to apply tone mapping and color space conversion at an arbitrary point
  5982. * in the effect chain.
  5983. *
  5984. * When applying tone mapping and color space conversion manually with this node,
  5985. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  5986. *
  5987. * ```js
  5988. * const postProcessing = new PostProcessing( renderer );
  5989. * postProcessing.outputColorTransform = false;
  5990. *
  5991. * const scenePass = pass( scene, camera );
  5992. * const outputPass = renderOutput( scenePass );
  5993. *
  5994. * postProcessing.outputNode = outputPass;
  5995. * ```
  5996. *
  5997. * @augments TempNode
  5998. */
  5999. class RenderOutputNode extends TempNode {
  6000. static get type() {
  6001. return 'RenderOutputNode';
  6002. }
  6003. /**
  6004. * Constructs a new render output node.
  6005. *
  6006. * @param {Node} colorNode - The color node to process.
  6007. * @param {Number} toneMapping - The tone mapping type.
  6008. * @param {String} outputColorSpace - The output color space.
  6009. */
  6010. constructor( colorNode, toneMapping, outputColorSpace ) {
  6011. super( 'vec4' );
  6012. /**
  6013. * The color node to process.
  6014. *
  6015. * @type {Node}
  6016. */
  6017. this.colorNode = colorNode;
  6018. /**
  6019. * The tone mapping type.
  6020. *
  6021. * @type {Number?}
  6022. */
  6023. this.toneMapping = toneMapping;
  6024. /**
  6025. * The output color space.
  6026. *
  6027. * @type {String?}
  6028. */
  6029. this.outputColorSpace = outputColorSpace;
  6030. /**
  6031. * This flag can be used for type testing.
  6032. *
  6033. * @type {Boolean}
  6034. * @readonly
  6035. * @default true
  6036. */
  6037. this.isRenderOutputNode = true;
  6038. }
  6039. setup( { context } ) {
  6040. let outputNode = this.colorNode || context.color;
  6041. // tone mapping
  6042. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6043. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6044. if ( toneMapping !== NoToneMapping ) {
  6045. outputNode = outputNode.toneMapping( toneMapping );
  6046. }
  6047. // working to output color space
  6048. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6049. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6050. }
  6051. return outputNode;
  6052. }
  6053. }
  6054. /**
  6055. * TSL function for creating a posterize node.
  6056. *
  6057. * @function
  6058. * @param {Node} color - The color node to process.
  6059. * @param {Number?} [toneMapping=null] - The tone mapping type.
  6060. * @param {String?} [outputColorSpace=null] - The output color space.
  6061. * @returns {RenderOutputNode}
  6062. */
  6063. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6064. addMethodChaining( 'renderOutput', renderOutput );
  6065. // Non-PURE exports list, side-effects are required here.
  6066. // TSL Base Syntax
  6067. function addNodeElement( name/*, nodeElement*/ ) {
  6068. console.warn( 'THREE.TSLBase: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6069. }
  6070. /** @module AttributeNode **/
  6071. /**
  6072. * Base class for representing shader attributes as nodes.
  6073. *
  6074. * @augments Node
  6075. */
  6076. class AttributeNode extends Node {
  6077. static get type() {
  6078. return 'AttributeNode';
  6079. }
  6080. /**
  6081. * Constructs a new attribute node.
  6082. *
  6083. * @param {String} attributeName - The name of the attribute.
  6084. * @param {String?} nodeType - The node type.
  6085. */
  6086. constructor( attributeName, nodeType = null ) {
  6087. super( nodeType );
  6088. /**
  6089. * `AttributeNode` sets this property to `true` by default.
  6090. *
  6091. * @type {Boolean}
  6092. * @default true
  6093. */
  6094. this.global = true;
  6095. this._attributeName = attributeName;
  6096. }
  6097. getHash( builder ) {
  6098. return this.getAttributeName( builder );
  6099. }
  6100. getNodeType( builder ) {
  6101. let nodeType = this.nodeType;
  6102. if ( nodeType === null ) {
  6103. const attributeName = this.getAttributeName( builder );
  6104. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6105. const attribute = builder.geometry.getAttribute( attributeName );
  6106. nodeType = builder.getTypeFromAttribute( attribute );
  6107. } else {
  6108. nodeType = 'float';
  6109. }
  6110. }
  6111. return nodeType;
  6112. }
  6113. /**
  6114. * Sets the attribute name to the given value. The method can be
  6115. * overwritten in derived classes if the final name must be computed
  6116. * analytically.
  6117. *
  6118. * @param {String} attributeName - The name of the attribute.
  6119. * @return {AttributeNode} A reference to this node.
  6120. */
  6121. setAttributeName( attributeName ) {
  6122. this._attributeName = attributeName;
  6123. return this;
  6124. }
  6125. /**
  6126. * Returns the attribute name of this node. The method can be
  6127. * overwritten in derived classes if the final name must be computed
  6128. * analytically.
  6129. *
  6130. * @param {NodeBuilder} builder - The current node builder.
  6131. * @return {String} The attribute name.
  6132. */
  6133. getAttributeName( /*builder*/ ) {
  6134. return this._attributeName;
  6135. }
  6136. generate( builder ) {
  6137. const attributeName = this.getAttributeName( builder );
  6138. const nodeType = this.getNodeType( builder );
  6139. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6140. if ( geometryAttribute === true ) {
  6141. const attribute = builder.geometry.getAttribute( attributeName );
  6142. const attributeType = builder.getTypeFromAttribute( attribute );
  6143. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6144. if ( builder.shaderStage === 'vertex' ) {
  6145. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6146. } else {
  6147. const nodeVarying = varying( this );
  6148. return nodeVarying.build( builder, nodeType );
  6149. }
  6150. } else {
  6151. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6152. return builder.generateConst( nodeType );
  6153. }
  6154. }
  6155. serialize( data ) {
  6156. super.serialize( data );
  6157. data.global = this.global;
  6158. data._attributeName = this._attributeName;
  6159. }
  6160. deserialize( data ) {
  6161. super.deserialize( data );
  6162. this.global = data.global;
  6163. this._attributeName = data._attributeName;
  6164. }
  6165. }
  6166. /**
  6167. * TSL function for creating an attribute node.
  6168. *
  6169. * @function
  6170. * @param {String} name - The name of the attribute.
  6171. * @param {String?} nodeType - The node type.
  6172. * @returns {AttributeNode}
  6173. */
  6174. const attribute = ( name, nodeType ) => nodeObject( new AttributeNode( name, nodeType ) );
  6175. /** @module UV **/
  6176. /**
  6177. * TSL function for creating an uv attribute node with the given index.
  6178. *
  6179. * @function
  6180. * @param {Number} [index=0] - The uv index.
  6181. * @return {AttributeNode<vec2>} The uv attribute node.
  6182. */
  6183. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6184. /** @module TextureSizeNode **/
  6185. /**
  6186. * A node that represents the dimensions of a texture. The texture size is
  6187. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6188. * or `textureSize()`.
  6189. *
  6190. * @augments Node
  6191. */
  6192. class TextureSizeNode extends Node {
  6193. static get type() {
  6194. return 'TextureSizeNode';
  6195. }
  6196. /**
  6197. * Constructs a new texture size node.
  6198. *
  6199. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6200. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6201. */
  6202. constructor( textureNode, levelNode = null ) {
  6203. super( 'uvec2' );
  6204. /**
  6205. * This flag can be used for type testing.
  6206. *
  6207. * @type {Boolean}
  6208. * @readonly
  6209. * @default true
  6210. */
  6211. this.isTextureSizeNode = true;
  6212. /**
  6213. * A texture node which size should be retrieved.
  6214. *
  6215. * @type {TextureNode}
  6216. */
  6217. this.textureNode = textureNode;
  6218. /**
  6219. * A level node which defines the requested mip.
  6220. *
  6221. * @type {Node<int>}
  6222. * @default null
  6223. */
  6224. this.levelNode = levelNode;
  6225. }
  6226. generate( builder, output ) {
  6227. const textureProperty = this.textureNode.build( builder, 'property' );
  6228. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  6229. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  6230. }
  6231. }
  6232. /**
  6233. * TSL function for creating a texture size node.
  6234. *
  6235. * @function
  6236. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  6237. * @param {Node<int>?} [levelNode=null] - A level node which defines the requested mip.
  6238. * @returns {TextureSizeNode}
  6239. */
  6240. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode );
  6241. /** @module MatcapUVNode **/
  6242. /**
  6243. * A special type of uniform node that computes the
  6244. * maximum mipmap level for a given texture node.
  6245. *
  6246. * ```js
  6247. * const level = maxMipLevel( textureNode );
  6248. * ```
  6249. *
  6250. * @augments module:UniformNode~UniformNode
  6251. */
  6252. class MaxMipLevelNode extends UniformNode {
  6253. static get type() {
  6254. return 'MaxMipLevelNode';
  6255. }
  6256. /**
  6257. * Constructs a new max mip level node.
  6258. *
  6259. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6260. */
  6261. constructor( textureNode ) {
  6262. super( 0 );
  6263. /**
  6264. * The texture node to compute the max mip level for.
  6265. *
  6266. * @private
  6267. * @type {TextureNode}
  6268. */
  6269. this._textureNode = textureNode;
  6270. /**
  6271. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  6272. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  6273. *
  6274. * @type {String}
  6275. * @default 'frame'
  6276. */
  6277. this.updateType = NodeUpdateType.FRAME;
  6278. }
  6279. /**
  6280. * The texture node to compute the max mip level for.
  6281. *
  6282. * @readonly
  6283. * @type {TextureNode}
  6284. */
  6285. get textureNode() {
  6286. return this._textureNode;
  6287. }
  6288. /**
  6289. * The texture.
  6290. *
  6291. * @readonly
  6292. * @type {Texture}
  6293. */
  6294. get texture() {
  6295. return this._textureNode.value;
  6296. }
  6297. update() {
  6298. const texture = this.texture;
  6299. const images = texture.images;
  6300. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  6301. if ( image && image.width !== undefined ) {
  6302. const { width, height } = image;
  6303. this.value = Math.log2( Math.max( width, height ) );
  6304. }
  6305. }
  6306. }
  6307. /**
  6308. * TSL function for creating a max mip level node.
  6309. *
  6310. * @function
  6311. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  6312. * @returns {MaxMipLevelNode}
  6313. */
  6314. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode );
  6315. /** @module TextureNode **/
  6316. /**
  6317. * This type of uniform node represents a 2D texture.
  6318. *
  6319. * @augments module:UniformNode~UniformNode
  6320. */
  6321. class TextureNode extends UniformNode {
  6322. static get type() {
  6323. return 'TextureNode';
  6324. }
  6325. /**
  6326. * Constructs a new texture node.
  6327. *
  6328. * @param {Texture} value - The texture.
  6329. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6330. * @param {Node<int>?} [levelNode=null] - The level node.
  6331. * @param {Node<float>?} [biasNode=null] - The bias node.
  6332. */
  6333. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  6334. super( value );
  6335. /**
  6336. * This flag can be used for type testing.
  6337. *
  6338. * @type {Boolean}
  6339. * @readonly
  6340. * @default true
  6341. */
  6342. this.isTextureNode = true;
  6343. /**
  6344. * Represents the texture coordinates.
  6345. *
  6346. * @type {Node<vec2|vec3>?}
  6347. * @default null
  6348. */
  6349. this.uvNode = uvNode;
  6350. /**
  6351. * Represents the mip level that should be selected.
  6352. *
  6353. * @type {Node<int>?}
  6354. * @default null
  6355. */
  6356. this.levelNode = levelNode;
  6357. /**
  6358. * Represents the bias to be applied during level-of-detail computation.
  6359. *
  6360. * @type {Node<float>?}
  6361. * @default null
  6362. */
  6363. this.biasNode = biasNode;
  6364. /**
  6365. * Represents a reference value a texture sample is compared to.
  6366. *
  6367. * @type {Node<float>?}
  6368. * @default null
  6369. */
  6370. this.compareNode = null;
  6371. /**
  6372. * When using texture arrays, the depth node defines the layer to select.
  6373. *
  6374. * @type {Node<int>?}
  6375. * @default null
  6376. */
  6377. this.depthNode = null;
  6378. /**
  6379. * When defined, a texture is sampled using explicit gradients.
  6380. *
  6381. * @type {Array<Node<vec2>>?}
  6382. * @default null
  6383. */
  6384. this.gradNode = null;
  6385. /**
  6386. * Whether texture values should be sampled or fetched.
  6387. *
  6388. * @type {Boolean}
  6389. * @default true
  6390. */
  6391. this.sampler = true;
  6392. /**
  6393. * Whether the uv transformation matrix should be
  6394. * automatically updated or not. Use `setUpdateMatrix()`
  6395. * if you want to change the value of the property.
  6396. *
  6397. * @type {Boolean}
  6398. * @default false
  6399. */
  6400. this.updateMatrix = false;
  6401. /**
  6402. * By default the `update()` method is not executed. `setUpdateMatrix()`
  6403. * sets the value to `frame` when the uv transformation matrix should
  6404. * automatically be updated.
  6405. *
  6406. * @type {String}
  6407. * @default 'none'
  6408. */
  6409. this.updateType = NodeUpdateType.NONE;
  6410. /**
  6411. * The reference node.
  6412. *
  6413. * @type {Node?}
  6414. * @default null
  6415. */
  6416. this.referenceNode = null;
  6417. /**
  6418. * The texture value is stored in a private property.
  6419. *
  6420. * @private
  6421. * @type {Texture}
  6422. */
  6423. this._value = value;
  6424. /**
  6425. * The uniform node that represents the uv transformation matrix.
  6426. *
  6427. * @private
  6428. * @type {UniformNode<mat3>?}
  6429. */
  6430. this._matrixUniform = null;
  6431. this.setUpdateMatrix( uvNode === null );
  6432. }
  6433. set value( value ) {
  6434. if ( this.referenceNode ) {
  6435. this.referenceNode.value = value;
  6436. } else {
  6437. this._value = value;
  6438. }
  6439. }
  6440. /**
  6441. * The texture value.
  6442. *
  6443. * @type {Texture}
  6444. */
  6445. get value() {
  6446. return this.referenceNode ? this.referenceNode.value : this._value;
  6447. }
  6448. /**
  6449. * Overwritten since the uniform hash is defined by the texture's UUID.
  6450. *
  6451. * @param {NodeBuilder} builder - The current node builder.
  6452. * @return {String} The uniform hash.
  6453. */
  6454. getUniformHash( /*builder*/ ) {
  6455. return this.value.uuid;
  6456. }
  6457. /**
  6458. * Overwritten since the node type is inferred from the texture type.
  6459. *
  6460. * @param {NodeBuilder} builder - The current node builder.
  6461. * @return {String} The node type.
  6462. */
  6463. getNodeType( /*builder*/ ) {
  6464. if ( this.value.isDepthTexture === true ) return 'float';
  6465. if ( this.value.type === UnsignedIntType ) {
  6466. return 'uvec4';
  6467. } else if ( this.value.type === IntType ) {
  6468. return 'ivec4';
  6469. }
  6470. return 'vec4';
  6471. }
  6472. /**
  6473. * Overwrites the default implementation to return a fixed value `'texture'`.
  6474. *
  6475. * @param {NodeBuilder} builder - The current node builder.
  6476. * @return {String} The input type.
  6477. */
  6478. getInputType( /*builder*/ ) {
  6479. return 'texture';
  6480. }
  6481. /**
  6482. * Returns a default uvs based on the current texture's channel.
  6483. *
  6484. * @return {AttributeNode<vec2>} The default uvs.
  6485. */
  6486. getDefaultUV() {
  6487. return uv( this.value.channel );
  6488. }
  6489. /**
  6490. * Overwritten to always return the texture reference of the node.
  6491. *
  6492. * @param {Any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  6493. * @return {Texture} The texture reference.
  6494. */
  6495. updateReference( /*state*/ ) {
  6496. return this.value;
  6497. }
  6498. /**
  6499. * Transforms the given uv node with the texture transformation matrix.
  6500. *
  6501. * @param {Node} uvNode - The uv node to transform.
  6502. * @return {Node} The transformed uv node.
  6503. */
  6504. getTransformedUV( uvNode ) {
  6505. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  6506. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  6507. }
  6508. /**
  6509. * Defines whether the uv transformation matrix should automatically be updated or not.
  6510. *
  6511. * @param {Boolean} value - The update toggle.
  6512. * @return {TextureNode} A reference to this node.
  6513. */
  6514. setUpdateMatrix( value ) {
  6515. this.updateMatrix = value;
  6516. this.updateType = value ? NodeUpdateType.RENDER : NodeUpdateType.NONE;
  6517. return this;
  6518. }
  6519. /**
  6520. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  6521. * to modify the uv node for correct sampling.
  6522. *
  6523. * @param {NodeBuilder} builder - The current node builder.
  6524. * @param {Node} uvNode - The uv node to setup.
  6525. * @return {Node} The updated uv node.
  6526. */
  6527. setupUV( builder, uvNode ) {
  6528. const texture = this.value;
  6529. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  6530. if ( this.sampler ) {
  6531. uvNode = uvNode.flipY();
  6532. } else {
  6533. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  6534. }
  6535. }
  6536. return uvNode;
  6537. }
  6538. /**
  6539. * Setups texture node by preparing the internal nodes for code generation.
  6540. *
  6541. * @param {NodeBuilder} builder - The current node builder.
  6542. */
  6543. setup( builder ) {
  6544. const properties = builder.getNodeProperties( this );
  6545. properties.referenceNode = this.referenceNode;
  6546. //
  6547. const texture = this.value;
  6548. if ( ! texture || texture.isTexture !== true ) {
  6549. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  6550. }
  6551. //
  6552. let uvNode = this.uvNode;
  6553. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  6554. uvNode = builder.context.getUV( this );
  6555. }
  6556. if ( ! uvNode ) uvNode = this.getDefaultUV();
  6557. if ( this.updateMatrix === true ) {
  6558. uvNode = this.getTransformedUV( uvNode );
  6559. }
  6560. uvNode = this.setupUV( builder, uvNode );
  6561. //
  6562. let levelNode = this.levelNode;
  6563. if ( levelNode === null && builder.context.getTextureLevel ) {
  6564. levelNode = builder.context.getTextureLevel( this );
  6565. }
  6566. //
  6567. properties.uvNode = uvNode;
  6568. properties.levelNode = levelNode;
  6569. properties.biasNode = this.biasNode;
  6570. properties.compareNode = this.compareNode;
  6571. properties.gradNode = this.gradNode;
  6572. properties.depthNode = this.depthNode;
  6573. }
  6574. /**
  6575. * Generates the uv code snippet.
  6576. *
  6577. * @param {NodeBuilder} builder - The current node builder.
  6578. * @param {Node} uvNode - The uv node to generate code for.
  6579. * @return {String} The generated code snippet.
  6580. */
  6581. generateUV( builder, uvNode ) {
  6582. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  6583. }
  6584. /**
  6585. * Generates the snippet for the texture sampling.
  6586. *
  6587. * @param {NodeBuilder} builder - The current node builder.
  6588. * @param {String} textureProperty - The texture property.
  6589. * @param {String} uvSnippet - The uv snippet.
  6590. * @param {String?} levelSnippet - The level snippet.
  6591. * @param {String?} biasSnippet - The bias snippet.
  6592. * @param {String?} depthSnippet - The depth snippet.
  6593. * @param {String?} compareSnippet - The compare snippet.
  6594. * @param {Array<String>?} gradSnippet - The grad snippet.
  6595. * @return {String} The generated code snippet.
  6596. */
  6597. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  6598. const texture = this.value;
  6599. let snippet;
  6600. if ( levelSnippet ) {
  6601. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  6602. } else if ( biasSnippet ) {
  6603. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  6604. } else if ( gradSnippet ) {
  6605. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  6606. } else if ( compareSnippet ) {
  6607. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  6608. } else if ( this.sampler === false ) {
  6609. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  6610. } else {
  6611. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  6612. }
  6613. return snippet;
  6614. }
  6615. /**
  6616. * Generates the code snippet of the texture node.
  6617. *
  6618. * @param {NodeBuilder} builder - The current node builder.
  6619. * @param {String} output - The current output.
  6620. * @return {String} The generated code snippet.
  6621. */
  6622. generate( builder, output ) {
  6623. const texture = this.value;
  6624. const properties = builder.getNodeProperties( this );
  6625. const textureProperty = super.generate( builder, 'property' );
  6626. if ( output === 'sampler' ) {
  6627. return textureProperty + '_sampler';
  6628. } else if ( builder.isReference( output ) ) {
  6629. return textureProperty;
  6630. } else {
  6631. const nodeData = builder.getDataFromNode( this );
  6632. let propertyName = nodeData.propertyName;
  6633. if ( propertyName === undefined ) {
  6634. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  6635. const uvSnippet = this.generateUV( builder, uvNode );
  6636. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  6637. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  6638. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  6639. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  6640. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  6641. const nodeVar = builder.getVarFromNode( this );
  6642. propertyName = builder.getPropertyName( nodeVar );
  6643. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  6644. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  6645. nodeData.snippet = snippet;
  6646. nodeData.propertyName = propertyName;
  6647. }
  6648. let snippet = propertyName;
  6649. const nodeType = this.getNodeType( builder );
  6650. if ( builder.needsToWorkingColorSpace( texture ) ) {
  6651. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  6652. }
  6653. return builder.format( snippet, nodeType, output );
  6654. }
  6655. }
  6656. /**
  6657. * Sets the sampler value.
  6658. *
  6659. * @param {Boolean} value - The sampler value to set.
  6660. * @return {TextureNode} A reference to this texture node.
  6661. */
  6662. setSampler( value ) {
  6663. this.sampler = value;
  6664. return this;
  6665. }
  6666. /**
  6667. * Returns the sampler value.
  6668. *
  6669. * @return {Boolean} The sampler value.
  6670. */
  6671. getSampler() {
  6672. return this.sampler;
  6673. }
  6674. // @TODO: Move to TSL
  6675. /**
  6676. * @function
  6677. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  6678. *
  6679. * @param {Node} uvNode - The uv node.
  6680. * @return {TextureNode} A texture node representing the texture sample.
  6681. */
  6682. uv( uvNode ) { // @deprecated, r172
  6683. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  6684. return this.sample( uvNode );
  6685. }
  6686. /**
  6687. * Samples the texture with the given uv node.
  6688. *
  6689. * @param {Node} uvNode - The uv node.
  6690. * @return {TextureNode} A texture node representing the texture sample.
  6691. */
  6692. sample( uvNode ) {
  6693. const textureNode = this.clone();
  6694. textureNode.uvNode = nodeObject( uvNode );
  6695. textureNode.referenceNode = this.getSelf();
  6696. return nodeObject( textureNode );
  6697. }
  6698. /**
  6699. * Samples a blurred version of the texture by defining an internal bias.
  6700. *
  6701. * @param {Node<float>} amountNode - How blurred the texture should be.
  6702. * @return {TextureNode} A texture node representing the texture sample.
  6703. */
  6704. blur( amountNode ) {
  6705. const textureNode = this.clone();
  6706. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  6707. textureNode.referenceNode = this.getSelf();
  6708. return nodeObject( textureNode );
  6709. }
  6710. /**
  6711. * Samples a specific mip of the texture.
  6712. *
  6713. * @param {Node<int>} levelNode - The mip level to sample.
  6714. * @return {TextureNode} A texture node representing the texture sample.
  6715. */
  6716. level( levelNode ) {
  6717. const textureNode = this.clone();
  6718. textureNode.levelNode = nodeObject( levelNode );
  6719. textureNode.referenceNode = this.getSelf();
  6720. return nodeObject( textureNode );
  6721. }
  6722. /**
  6723. * Returns the texture size of the requested level.
  6724. *
  6725. * @param {Node<int>} levelNode - The level to compute the size for.
  6726. * @return {TextureSizeNode} The texture size.
  6727. */
  6728. size( levelNode ) {
  6729. return textureSize( this, levelNode );
  6730. }
  6731. /**
  6732. * Samples the texture with the given bias.
  6733. *
  6734. * @param {Node<float>} biasNode - The bias node.
  6735. * @return {TextureNode} A texture node representing the texture sample.
  6736. */
  6737. bias( biasNode ) {
  6738. const textureNode = this.clone();
  6739. textureNode.biasNode = nodeObject( biasNode );
  6740. textureNode.referenceNode = this.getSelf();
  6741. return nodeObject( textureNode );
  6742. }
  6743. /**
  6744. * Samples the texture by executing a compare operation.
  6745. *
  6746. * @param {Node<float>} compareNode - The node that defines the compare value.
  6747. * @return {TextureNode} A texture node representing the texture sample.
  6748. */
  6749. compare( compareNode ) {
  6750. const textureNode = this.clone();
  6751. textureNode.compareNode = nodeObject( compareNode );
  6752. textureNode.referenceNode = this.getSelf();
  6753. return nodeObject( textureNode );
  6754. }
  6755. /**
  6756. * Samples the texture using an explicit gradient.
  6757. *
  6758. * @param {Node<vec2>} gradNodeX - The gradX node.
  6759. * @param {Node<vec2>} gradNodeY - The gradY node.
  6760. * @return {TextureNode} A texture node representing the texture sample.
  6761. */
  6762. grad( gradNodeX, gradNodeY ) {
  6763. const textureNode = this.clone();
  6764. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  6765. textureNode.referenceNode = this.getSelf();
  6766. return nodeObject( textureNode );
  6767. }
  6768. /**
  6769. * Samples the texture by defining a depth node.
  6770. *
  6771. * @param {Node<int>} depthNode - The depth node.
  6772. * @return {TextureNode} A texture node representing the texture sample.
  6773. */
  6774. depth( depthNode ) {
  6775. const textureNode = this.clone();
  6776. textureNode.depthNode = nodeObject( depthNode );
  6777. textureNode.referenceNode = this.getSelf();
  6778. return nodeObject( textureNode );
  6779. }
  6780. // --
  6781. serialize( data ) {
  6782. super.serialize( data );
  6783. data.value = this.value.toJSON( data.meta ).uuid;
  6784. data.sampler = this.sampler;
  6785. data.updateMatrix = this.updateMatrix;
  6786. data.updateType = this.updateType;
  6787. }
  6788. deserialize( data ) {
  6789. super.deserialize( data );
  6790. this.value = data.meta.textures[ data.value ];
  6791. this.sampler = data.sampler;
  6792. this.updateMatrix = data.updateMatrix;
  6793. this.updateType = data.updateType;
  6794. }
  6795. /**
  6796. * The update is used to implement the update of the uv transformation matrix.
  6797. */
  6798. update() {
  6799. const texture = this.value;
  6800. const matrixUniform = this._matrixUniform;
  6801. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  6802. if ( texture.matrixAutoUpdate === true ) {
  6803. texture.updateMatrix();
  6804. }
  6805. }
  6806. /**
  6807. * Clones the texture node.
  6808. *
  6809. * @return {TextureNode} The cloned texture node.
  6810. */
  6811. clone() {
  6812. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  6813. newNode.sampler = this.sampler;
  6814. return newNode;
  6815. }
  6816. }
  6817. /**
  6818. * TSL function for creating a texture node.
  6819. *
  6820. * @function
  6821. * @param {Texture} value - The texture.
  6822. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6823. * @param {Node<int>?} [levelNode=null] - The level node.
  6824. * @param {Node<float>?} [biasNode=null] - The bias node.
  6825. * @returns {TextureNode}
  6826. */
  6827. const texture = /*@__PURE__*/ nodeProxy( TextureNode );
  6828. /**
  6829. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  6830. *
  6831. * @function
  6832. * @param {Texture} value - The texture.
  6833. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  6834. * @param {Node<int>?} [levelNode=null] - The level node.
  6835. * @param {Node<float>?} [biasNode=null] - The bias node.
  6836. * @returns {TextureNode}
  6837. */
  6838. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  6839. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  6840. /**
  6841. * Converts a texture or texture node to a sampler.
  6842. *
  6843. * @function
  6844. * @param {TextureNode|Texture} aTexture - The texture or texture node to convert.
  6845. * @returns {Node}
  6846. */
  6847. const sampler = ( aTexture ) => ( aTexture.isNode === true ? aTexture : texture( aTexture ) ).convert( 'sampler' );
  6848. /** @module BufferNode **/
  6849. /**
  6850. * A special type of uniform node which represents array-like data
  6851. * as uniform buffers. The access usually happens via `element()`
  6852. * which returns an instance of {@link ArrayElementNode}. For example:
  6853. *
  6854. * ```js
  6855. * const bufferNode = buffer( array, 'mat4', count );
  6856. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  6857. * ```
  6858. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  6859. * since it handles more input types and automatically cares about buffer paddings.
  6860. *
  6861. * @augments module:UniformNode~UniformNode
  6862. */
  6863. class BufferNode extends UniformNode {
  6864. static get type() {
  6865. return 'BufferNode';
  6866. }
  6867. /**
  6868. * Constructs a new buffer node.
  6869. *
  6870. * @param {Array<Number>} value - Array-like buffer data.
  6871. * @param {String} bufferType - The data type of the buffer.
  6872. * @param {Number} [bufferCount=0] - The count of buffer elements.
  6873. */
  6874. constructor( value, bufferType, bufferCount = 0 ) {
  6875. super( value, bufferType );
  6876. /**
  6877. * This flag can be used for type testing.
  6878. *
  6879. * @type {Boolean}
  6880. * @readonly
  6881. * @default true
  6882. */
  6883. this.isBufferNode = true;
  6884. /**
  6885. * The data type of the buffer.
  6886. *
  6887. * @type {String}
  6888. */
  6889. this.bufferType = bufferType;
  6890. /**
  6891. * The uniform node that holds the value of the reference node.
  6892. *
  6893. * @type {Number}
  6894. * @default 0
  6895. */
  6896. this.bufferCount = bufferCount;
  6897. }
  6898. /**
  6899. * The data type of the buffer elements.
  6900. *
  6901. * @param {NodeBuilder} builder - The current node builder.
  6902. * @return {String} The element type.
  6903. */
  6904. getElementType( builder ) {
  6905. return this.getNodeType( builder );
  6906. }
  6907. /**
  6908. * Overwrites the default implementation to return a fixed value `'buffer'`.
  6909. *
  6910. * @param {NodeBuilder} builder - The current node builder.
  6911. * @return {String} The input type.
  6912. */
  6913. getInputType( /*builder*/ ) {
  6914. return 'buffer';
  6915. }
  6916. }
  6917. /**
  6918. * TSL function for creating a buffer node.
  6919. *
  6920. * @function
  6921. * @param {Array} value - Array-like buffer data.
  6922. * @param {String} type - The data type of a buffer element.
  6923. * @param {Number} count - The count of buffer elements.
  6924. * @returns {BufferNode}
  6925. */
  6926. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  6927. /** @module UniformArrayNode **/
  6928. /**
  6929. * Represents the element access on uniform array nodes.
  6930. *
  6931. * @augments ArrayElementNode
  6932. */
  6933. class UniformArrayElementNode extends ArrayElementNode {
  6934. static get type() {
  6935. return 'UniformArrayElementNode';
  6936. }
  6937. /**
  6938. * Constructs a new buffer node.
  6939. *
  6940. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  6941. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  6942. */
  6943. constructor( uniformArrayNode, indexNode ) {
  6944. super( uniformArrayNode, indexNode );
  6945. /**
  6946. * This flag can be used for type testing.
  6947. *
  6948. * @type {Boolean}
  6949. * @readonly
  6950. * @default true
  6951. */
  6952. this.isArrayBufferElementNode = true;
  6953. }
  6954. generate( builder ) {
  6955. const snippet = super.generate( builder );
  6956. const type = this.getNodeType();
  6957. const paddedType = this.node.getPaddedType();
  6958. return builder.format( snippet, paddedType, type );
  6959. }
  6960. }
  6961. /**
  6962. * Similar to {@link module:BufferNode~BufferNode} this module represents array-like data as
  6963. * uniform buffers. Unlike {@link module:BufferNode~BufferNode}, it can handle more common
  6964. * data types in the array (e.g `three.js` primitives) and automatically
  6965. * manage buffer padding. It should be the first choice when working with
  6966. * uniforms buffers.
  6967. * ```js
  6968. * const tintColors = uniformArray( [
  6969. * new Color( 1, 0, 0 ),
  6970. * new Color( 0, 1, 0 ),
  6971. * new Color( 0, 0, 1 )
  6972. * ], 'color' );
  6973. *
  6974. * const redColor = tintColors.element( 0 );
  6975. *
  6976. * @augments module:BufferNode~BufferNode
  6977. */
  6978. class UniformArrayNode extends BufferNode {
  6979. static get type() {
  6980. return 'UniformArrayNode';
  6981. }
  6982. /**
  6983. * Constructs a new uniform array node.
  6984. *
  6985. * @param {Array<Any>} value - Array holding the buffer data.
  6986. * @param {String?} [elementType=null] - The data type of a buffer element.
  6987. */
  6988. constructor( value, elementType = null ) {
  6989. super( null );
  6990. /**
  6991. * Array holding the buffer data. Unlike {@link module:BufferNode~BufferNode}, the array can
  6992. * hold number primitives as well as three.js objects like vectors, matrices
  6993. * or colors.
  6994. *
  6995. * @type {Array<Any>}
  6996. */
  6997. this.array = value;
  6998. /**
  6999. * The data type of an array element.
  7000. *
  7001. * @type {String}
  7002. */
  7003. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7004. /**
  7005. * The padded type. Uniform buffers must conform to a certain buffer layout
  7006. * so a separate type is computed to ensure correct buffer size.
  7007. *
  7008. * @type {String}
  7009. */
  7010. this.paddedType = this.getPaddedType();
  7011. /**
  7012. * Overwritten since uniform array nodes are updated per render.
  7013. *
  7014. * @type {String}
  7015. * @default 'render'
  7016. */
  7017. this.updateType = NodeUpdateType.RENDER;
  7018. /**
  7019. * This flag can be used for type testing.
  7020. *
  7021. * @type {Boolean}
  7022. * @readonly
  7023. * @default true
  7024. */
  7025. this.isArrayBufferNode = true;
  7026. }
  7027. /**
  7028. * This method is overwritten since the node type is inferred from the
  7029. * {@link module:UniformArrayNode~UniformArrayNode#paddedType}.
  7030. *
  7031. * @param {NodeBuilder} builder - The current node builder.
  7032. * @return {String} The node type.
  7033. */
  7034. getNodeType( /*builder*/ ) {
  7035. return this.paddedType;
  7036. }
  7037. /**
  7038. * The data type of the array elements.
  7039. *
  7040. * @param {NodeBuilder} builder - The current node builder.
  7041. * @return {String} The element type.
  7042. */
  7043. getElementType() {
  7044. return this.elementType;
  7045. }
  7046. /**
  7047. * Returns the padded type based on the element type.
  7048. *
  7049. * @return {String} The padded type.
  7050. */
  7051. getPaddedType() {
  7052. const elementType = this.elementType;
  7053. let paddedType = 'vec4';
  7054. if ( elementType === 'mat2' ) {
  7055. paddedType = 'mat2';
  7056. } else if ( /mat/.test( elementType ) === true ) {
  7057. paddedType = 'mat4';
  7058. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7059. paddedType = 'ivec4';
  7060. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7061. paddedType = 'uvec4';
  7062. }
  7063. return paddedType;
  7064. }
  7065. /**
  7066. * The update makes sure to correctly transfer the data from the (complex) objects
  7067. * in the array to the internal, correctly padded value buffer.
  7068. *
  7069. * @param {NodeFrame} frame - A reference to the current node frame.
  7070. */
  7071. update( /*frame*/ ) {
  7072. const { array, value } = this;
  7073. const elementType = this.elementType;
  7074. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7075. for ( let i = 0; i < array.length; i ++ ) {
  7076. const index = i * 4;
  7077. value[ index ] = array[ i ];
  7078. }
  7079. } else if ( elementType === 'color' ) {
  7080. for ( let i = 0; i < array.length; i ++ ) {
  7081. const index = i * 4;
  7082. const vector = array[ i ];
  7083. value[ index ] = vector.r;
  7084. value[ index + 1 ] = vector.g;
  7085. value[ index + 2 ] = vector.b || 0;
  7086. //value[ index + 3 ] = vector.a || 0;
  7087. }
  7088. } else if ( elementType === 'mat2' ) {
  7089. for ( let i = 0; i < array.length; i ++ ) {
  7090. const index = i * 4;
  7091. const matrix = array[ i ];
  7092. value[ index ] = matrix.elements[ 0 ];
  7093. value[ index + 1 ] = matrix.elements[ 1 ];
  7094. value[ index + 2 ] = matrix.elements[ 2 ];
  7095. value[ index + 3 ] = matrix.elements[ 3 ];
  7096. }
  7097. } else if ( elementType === 'mat3' ) {
  7098. for ( let i = 0; i < array.length; i ++ ) {
  7099. const index = i * 16;
  7100. const matrix = array[ i ];
  7101. value[ index ] = matrix.elements[ 0 ];
  7102. value[ index + 1 ] = matrix.elements[ 1 ];
  7103. value[ index + 2 ] = matrix.elements[ 2 ];
  7104. value[ index + 4 ] = matrix.elements[ 3 ];
  7105. value[ index + 5 ] = matrix.elements[ 4 ];
  7106. value[ index + 6 ] = matrix.elements[ 5 ];
  7107. value[ index + 8 ] = matrix.elements[ 6 ];
  7108. value[ index + 9 ] = matrix.elements[ 7 ];
  7109. value[ index + 10 ] = matrix.elements[ 8 ];
  7110. value[ index + 15 ] = 1;
  7111. }
  7112. } else if ( elementType === 'mat4' ) {
  7113. for ( let i = 0; i < array.length; i ++ ) {
  7114. const index = i * 16;
  7115. const matrix = array[ i ];
  7116. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7117. value[ index + i ] = matrix.elements[ i ];
  7118. }
  7119. }
  7120. } else {
  7121. for ( let i = 0; i < array.length; i ++ ) {
  7122. const index = i * 4;
  7123. const vector = array[ i ];
  7124. value[ index ] = vector.x;
  7125. value[ index + 1 ] = vector.y;
  7126. value[ index + 2 ] = vector.z || 0;
  7127. value[ index + 3 ] = vector.w || 0;
  7128. }
  7129. }
  7130. }
  7131. /**
  7132. * Implement the value buffer creation based on the array data.
  7133. *
  7134. * @param {NodeBuilder} builder - A reference to the current node builder.
  7135. * @return {null}
  7136. */
  7137. setup( builder ) {
  7138. const length = this.array.length;
  7139. const elementType = this.elementType;
  7140. let arrayType = Float32Array;
  7141. const paddedType = this.paddedType;
  7142. const paddedElementLength = builder.getTypeLength( paddedType );
  7143. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  7144. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  7145. this.value = new arrayType( length * paddedElementLength );
  7146. this.bufferCount = length;
  7147. this.bufferType = paddedType;
  7148. return super.setup( builder );
  7149. }
  7150. /**
  7151. * Overwrites the default `element()` method to provide element access
  7152. * based on {@link module:UniformArrayNode~UniformArrayNode}.
  7153. *
  7154. * @param {IndexNode} indexNode - The index node.
  7155. * @return {UniformArrayElementNode}
  7156. */
  7157. element( indexNode ) {
  7158. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  7159. }
  7160. }
  7161. /**
  7162. * TSL function for creating an uniform array node.
  7163. *
  7164. * @function
  7165. * @param {Array<Any>} values - Array-like data.
  7166. * @param {String?} nodeType - The data type of the array elements.
  7167. * @returns {UniformArrayNode}
  7168. */
  7169. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  7170. /**
  7171. * @function
  7172. * @deprecated since r168. Use {@link uniformArray} instead.
  7173. *
  7174. * @param {Array<Any>} values - Array-like data.
  7175. * @param {String} nodeType - The data type of the array elements.
  7176. * @returns {UniformArrayNode}
  7177. */
  7178. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  7179. console.warn( 'TSL.UniformArrayNode: uniforms() has been renamed to uniformArray().' );
  7180. return nodeObject( new UniformArrayNode( values, nodeType ) );
  7181. };
  7182. /** @module Camera **/
  7183. /**
  7184. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  7185. *
  7186. * @type {UniformNode<uint>}
  7187. */
  7188. const cameraIndex = /*@__PURE__*/ uniform( 'uint' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).vertexStage();
  7189. /**
  7190. * TSL object that represents the `near` value of the camera used for the current render.
  7191. *
  7192. * @type {UniformNode<float>}
  7193. */
  7194. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  7195. /**
  7196. * TSL object that represents the `far` value of the camera used for the current render.
  7197. *
  7198. * @type {UniformNode<float>}
  7199. */
  7200. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  7201. /**
  7202. * TSL object that represents the projection matrix of the camera used for the current render.
  7203. *
  7204. * @type {UniformNode<mat4>}
  7205. */
  7206. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7207. let cameraProjectionMatrix;
  7208. if ( camera.isArrayCamera ) {
  7209. const matrices = [];
  7210. for ( const subCamera of camera.cameras ) {
  7211. matrices.push( subCamera.projectionMatrix );
  7212. }
  7213. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  7214. cameraProjectionMatrix = cameraProjectionMatrices.element( cameraIndex ).toVar( 'cameraProjectionMatrix' );
  7215. } else {
  7216. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  7217. }
  7218. return cameraProjectionMatrix;
  7219. } ).once() )();
  7220. /**
  7221. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  7222. *
  7223. * @type {UniformNode<mat4>}
  7224. */
  7225. const cameraProjectionMatrixInverse = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  7226. /**
  7227. * TSL object that represents the view matrix of the camera used for the current render.
  7228. *
  7229. * @type {UniformNode<mat4>}
  7230. */
  7231. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  7232. let cameraViewMatrix;
  7233. if ( camera.isArrayCamera ) {
  7234. const matrices = [];
  7235. for ( const subCamera of camera.cameras ) {
  7236. matrices.push( subCamera.matrixWorldInverse );
  7237. }
  7238. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  7239. cameraViewMatrix = cameraViewMatrices.element( cameraIndex ).toVar( 'cameraViewMatrix' );
  7240. } else {
  7241. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  7242. }
  7243. return cameraViewMatrix;
  7244. } ).once() )();
  7245. /**
  7246. * TSL object that represents the world matrix of the camera used for the current render.
  7247. *
  7248. * @type {UniformNode<mat4>}
  7249. */
  7250. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  7251. /**
  7252. * TSL object that represents the normal matrix of the camera used for the current render.
  7253. *
  7254. * @type {UniformNode<mat3>}
  7255. */
  7256. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  7257. /**
  7258. * TSL object that represents the position in world space of the camera used for the current render.
  7259. *
  7260. * @type {UniformNode<vec3>}
  7261. */
  7262. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  7263. /** @module Object3DNode **/
  7264. /**
  7265. * This node can be used to access transformation related metrics of 3D objects.
  7266. * Depending on the selected scope, a different metric is represented as a uniform
  7267. * in the shader. The following scopes are supported:
  7268. *
  7269. * - `POSITION`: The object's position in world space.
  7270. * - `VIEW_POSITION`: The object's position in view/camera space.
  7271. * - `DIRECTION`: The object's direction in world space.
  7272. * - `SCALE`: The object's scale in world space.
  7273. * - `WORLD_MATRIX`: The object's matrix in world space.
  7274. *
  7275. * @augments Node
  7276. */
  7277. class Object3DNode extends Node {
  7278. static get type() {
  7279. return 'Object3DNode';
  7280. }
  7281. /**
  7282. * Constructs a new object 3D node.
  7283. *
  7284. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7285. * @param {Object3D?} [object3d=null] - The 3D object.
  7286. */
  7287. constructor( scope, object3d = null ) {
  7288. super();
  7289. /**
  7290. * The node reports a different type of transformation depending on the scope.
  7291. *
  7292. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  7293. */
  7294. this.scope = scope;
  7295. /**
  7296. * The 3D object.
  7297. *
  7298. * @type {Object3D?}
  7299. * @default null
  7300. */
  7301. this.object3d = object3d;
  7302. /**
  7303. * Overwritten since this type of node is updated per object.
  7304. *
  7305. * @type {String}
  7306. * @default 'object'
  7307. */
  7308. this.updateType = NodeUpdateType.OBJECT;
  7309. /**
  7310. * Holds the value of the node as a uniform.
  7311. *
  7312. * @private
  7313. * @type {UniformNode}
  7314. */
  7315. this._uniformNode = new UniformNode( null );
  7316. }
  7317. /**
  7318. * Overwritten since the node type is inferred from the scope.
  7319. *
  7320. * @return {String} The node type.
  7321. */
  7322. getNodeType() {
  7323. const scope = this.scope;
  7324. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7325. return 'mat4';
  7326. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7327. return 'vec3';
  7328. }
  7329. }
  7330. /**
  7331. * Updates the uniform value depending on the scope.
  7332. *
  7333. * @param {NodeFrame} frame - The current node frame.
  7334. */
  7335. update( frame ) {
  7336. const object = this.object3d;
  7337. const uniformNode = this._uniformNode;
  7338. const scope = this.scope;
  7339. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7340. uniformNode.value = object.matrixWorld;
  7341. } else if ( scope === Object3DNode.POSITION ) {
  7342. uniformNode.value = uniformNode.value || new Vector3();
  7343. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7344. } else if ( scope === Object3DNode.SCALE ) {
  7345. uniformNode.value = uniformNode.value || new Vector3();
  7346. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  7347. } else if ( scope === Object3DNode.DIRECTION ) {
  7348. uniformNode.value = uniformNode.value || new Vector3();
  7349. object.getWorldDirection( uniformNode.value );
  7350. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  7351. const camera = frame.camera;
  7352. uniformNode.value = uniformNode.value || new Vector3();
  7353. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  7354. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  7355. }
  7356. }
  7357. /**
  7358. * Generates the code snippet of the uniform node. The node type of the uniform
  7359. * node also depends on the selected scope.
  7360. *
  7361. * @param {NodeBuilder} builder - The current node builder.
  7362. * @return {String} The generated code snippet.
  7363. */
  7364. generate( builder ) {
  7365. const scope = this.scope;
  7366. if ( scope === Object3DNode.WORLD_MATRIX ) {
  7367. this._uniformNode.nodeType = 'mat4';
  7368. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  7369. this._uniformNode.nodeType = 'vec3';
  7370. }
  7371. return this._uniformNode.build( builder );
  7372. }
  7373. serialize( data ) {
  7374. super.serialize( data );
  7375. data.scope = this.scope;
  7376. }
  7377. deserialize( data ) {
  7378. super.deserialize( data );
  7379. this.scope = data.scope;
  7380. }
  7381. }
  7382. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  7383. Object3DNode.POSITION = 'position';
  7384. Object3DNode.SCALE = 'scale';
  7385. Object3DNode.VIEW_POSITION = 'viewPosition';
  7386. Object3DNode.DIRECTION = 'direction';
  7387. /**
  7388. * TSL function for creating an object 3D node that represents the object's direction in world space.
  7389. *
  7390. * @function
  7391. * @param {Object3D?} [object3d=null] - The 3D object.
  7392. * @returns {Object3DNode<vec3>}
  7393. */
  7394. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION );
  7395. /**
  7396. * TSL function for creating an object 3D node that represents the object's world matrix.
  7397. *
  7398. * @function
  7399. * @param {Object3D?} [object3d=null] - The 3D object.
  7400. * @returns {Object3DNode<mat4>}
  7401. */
  7402. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX );
  7403. /**
  7404. * TSL function for creating an object 3D node that represents the object's position in world space.
  7405. *
  7406. * @function
  7407. * @param {Object3D?} [object3d=null] - The 3D object.
  7408. * @returns {Object3DNode<vec3>}
  7409. */
  7410. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION );
  7411. /**
  7412. * TSL function for creating an object 3D node that represents the object's scale in world space.
  7413. *
  7414. * @function
  7415. * @param {Object3D?} [object3d=null] - The 3D object.
  7416. * @returns {Object3DNode<vec3>}
  7417. */
  7418. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE );
  7419. /**
  7420. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  7421. *
  7422. * @function
  7423. * @param {Object3D?} [object3d=null] - The 3D object.
  7424. * @returns {Object3DNode<vec3>}
  7425. */
  7426. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION );
  7427. /** @module ModelNode **/
  7428. /**
  7429. * This type of node is a specialized version of `Object3DNode`
  7430. * with larger set of model related metrics. Unlike `Object3DNode`,
  7431. * `ModelNode` extracts the reference to the 3D object from the
  7432. * current node frame state.
  7433. *
  7434. * @augments module:Object3DNode~Object3DNode
  7435. */
  7436. class ModelNode extends Object3DNode {
  7437. static get type() {
  7438. return 'ModelNode';
  7439. }
  7440. /**
  7441. * Constructs a new object model node.
  7442. *
  7443. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  7444. */
  7445. constructor( scope ) {
  7446. super( scope );
  7447. }
  7448. /**
  7449. * Extracts the model reference from the frame state and then
  7450. * updates the uniform value depending on the scope.
  7451. *
  7452. * @param {NodeFrame} frame - The current node frame.
  7453. */
  7454. update( frame ) {
  7455. this.object3d = frame.object;
  7456. super.update( frame );
  7457. }
  7458. }
  7459. /**
  7460. * TSL object that represents the object's direction in world space.
  7461. *
  7462. * @type {ModelNode<vec3>}
  7463. */
  7464. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  7465. /**
  7466. * TSL object that represents the object's world matrix.
  7467. *
  7468. * @type {ModelNode<mat4>}
  7469. */
  7470. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  7471. /**
  7472. * TSL object that represents the object's position in world space.
  7473. *
  7474. * @type {ModelNode<vec3>}
  7475. */
  7476. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  7477. /**
  7478. * TSL object that represents the object's scale in world space.
  7479. *
  7480. * @type {ModelNode<vec3>}
  7481. */
  7482. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  7483. /**
  7484. * TSL object that represents the object's position in view/camera space.
  7485. *
  7486. * @type {ModelNode<vec3>}
  7487. */
  7488. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  7489. /**
  7490. * TSL object that represents the object's normal matrix.
  7491. *
  7492. * @type {UniformNode<mat3>}
  7493. */
  7494. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  7495. /**
  7496. * TSL object that represents the object's inverse world matrix.
  7497. *
  7498. * @type {UniformNode<mat4>}
  7499. */
  7500. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  7501. /**
  7502. * TSL object that represents the object's model view matrix.
  7503. *
  7504. * @type {Node<mat4>}
  7505. */
  7506. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7507. return builder.renderer.nodes.modelViewMatrix || mediumpModelViewMatrix;
  7508. } ).once() )().toVar( 'modelViewMatrix' );
  7509. // GPU Precision
  7510. /**
  7511. * TSL object that represents the object's model view in `mediump` precision.
  7512. *
  7513. * @type {Node<mat4>}
  7514. */
  7515. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  7516. // CPU Precision
  7517. /**
  7518. * TSL object that represents the object's model view in `highp` precision
  7519. * which is achieved by computing the matrix in JS and not in the shader.
  7520. *
  7521. * @type {Node<mat4>}
  7522. */
  7523. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7524. builder.context.isHighPrecisionModelViewMatrix = true;
  7525. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  7526. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7527. } );
  7528. } ).once() )().toVar( 'highpModelViewMatrix' );
  7529. /**
  7530. * TSL object that represents the object's model normal view in `highp` precision
  7531. * which is achieved by computing the matrix in JS and not in the shader.
  7532. *
  7533. * @type {Node<mat3>}
  7534. */
  7535. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  7536. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  7537. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  7538. if ( isHighPrecisionModelViewMatrix !== true ) {
  7539. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  7540. }
  7541. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  7542. } );
  7543. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  7544. /** @module Position **/
  7545. /**
  7546. * TSL object that represents the position attribute of the current rendered object.
  7547. *
  7548. * @type {AttributeNode<vec3>}
  7549. */
  7550. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  7551. /**
  7552. * TSL object that represents the vertex position in local space of the current rendered object.
  7553. *
  7554. * @type {AttributeNode<vec3>}
  7555. */
  7556. const positionLocal = /*@__PURE__*/ positionGeometry.varying( 'positionLocal' );
  7557. /**
  7558. * TSL object that represents the previous vertex position in local space of the current rendered object.
  7559. * Used in context of {@link module:VelocityNode~VelocityNode} for rendering motion vectors.
  7560. *
  7561. * @type {AttributeNode<vec3>}
  7562. */
  7563. const positionPrevious = /*@__PURE__*/ positionGeometry.varying( 'positionPrevious' );
  7564. /**
  7565. * TSL object that represents the vertex position in world space of the current rendered object.
  7566. *
  7567. * @type {VaryingNode<vec3>}
  7568. */
  7569. const positionWorld = /*@__PURE__*/ modelWorldMatrix.mul( positionLocal ).xyz.varying( 'v_positionWorld' ).context( { needsPositionReassign: true } );
  7570. /**
  7571. * TSL object that represents the position world direction of the current rendered object.
  7572. *
  7573. * @type {Node<vec3>}
  7574. */
  7575. const positionWorldDirection = /*@__PURE__*/ positionLocal.transformDirection( modelWorldMatrix ).varying( 'v_positionWorldDirection' ).normalize().toVar( 'positionWorldDirection' ).context( { needsPositionReassign: true } );
  7576. /**
  7577. * TSL object that represents the vertex position in view space of the current rendered object.
  7578. *
  7579. * @type {VaryingNode<vec3>}
  7580. */
  7581. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7582. return builder.context.setupPositionView();
  7583. }, 'vec3' ).once() )().varying( 'v_positionView' ).context( { needsPositionReassign: true } );
  7584. /**
  7585. * TSL object that represents the position view direction of the current rendered object.
  7586. *
  7587. * @type {VaryingNode<vec3>}
  7588. */
  7589. const positionViewDirection = /*@__PURE__*/ positionView.negate().varying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  7590. /** @module FrontFacingNode **/
  7591. /**
  7592. * This node can be used to evaluate whether a primitive is front or back facing.
  7593. *
  7594. * @augments Node
  7595. */
  7596. class FrontFacingNode extends Node {
  7597. static get type() {
  7598. return 'FrontFacingNode';
  7599. }
  7600. /**
  7601. * Constructs a new front facing node.
  7602. */
  7603. constructor() {
  7604. super( 'bool' );
  7605. /**
  7606. * This flag can be used for type testing.
  7607. *
  7608. * @type {Boolean}
  7609. * @readonly
  7610. * @default true
  7611. */
  7612. this.isFrontFacingNode = true;
  7613. }
  7614. generate( builder ) {
  7615. const { renderer, material } = builder;
  7616. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  7617. if ( material.side === BackSide ) {
  7618. return 'false';
  7619. }
  7620. }
  7621. return builder.getFrontFacing();
  7622. }
  7623. }
  7624. /**
  7625. * TSL object that represents whether a primitive is front or back facing
  7626. *
  7627. * @type {FrontFacingNode<bool>}
  7628. */
  7629. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  7630. /**
  7631. * TSL object that represents the front facing status as a number instead of a bool.
  7632. * `1` means front facing, `-1` means back facing.
  7633. *
  7634. * @type {Node<float>}
  7635. */
  7636. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  7637. /** @module Normal **/
  7638. /**
  7639. * TSL object that represents the normal attribute of the current rendered object.
  7640. *
  7641. * @type {Node<vec3>}
  7642. */
  7643. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  7644. /**
  7645. * TSL object that represents the vertex normal in local space of the current rendered object.
  7646. *
  7647. * @type {Node<vec3>}
  7648. */
  7649. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  7650. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  7651. console.warn( 'TSL.NormalNode: Vertex attribute "normal" not found on geometry.' );
  7652. return vec3( 0, 1, 0 );
  7653. }
  7654. return normalGeometry;
  7655. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  7656. /**
  7657. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  7658. *
  7659. * @type {Node<vec3>}
  7660. */
  7661. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  7662. /**
  7663. * TSL object that represents the vertex normal in view space of the current rendered object.
  7664. *
  7665. * @type {Node<vec3>}
  7666. */
  7667. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7668. let node;
  7669. if ( builder.material.flatShading === true ) {
  7670. node = normalFlat;
  7671. } else {
  7672. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  7673. }
  7674. return node;
  7675. }, 'vec3' ).once() )().toVar( 'normalView' );
  7676. /**
  7677. * TSL object that represents the vertex normal in world space of the current rendered object.
  7678. *
  7679. * @type {Node<vec3>}
  7680. */
  7681. const normalWorld = /*@__PURE__*/ varying( normalView.transformDirection( cameraViewMatrix ), 'v_normalWorld' ).normalize().toVar( 'normalWorld' );
  7682. /**
  7683. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  7684. *
  7685. * @type {Node<vec3>}
  7686. */
  7687. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7688. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7689. return builder.context.setupNormal().context( { getUV: null } );
  7690. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedNormalView' );
  7691. /**
  7692. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  7693. *
  7694. * @type {Node<vec3>}
  7695. */
  7696. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  7697. /**
  7698. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  7699. *
  7700. * @type {Node<vec3>}
  7701. */
  7702. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  7703. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  7704. return builder.context.setupClearcoatNormal().context( { getUV: null } );
  7705. }, 'vec3' ).once() )().mul( faceDirection ).toVar( 'transformedClearcoatNormalView' );
  7706. /**
  7707. * Transforms the normal with the given matrix.
  7708. *
  7709. * @function
  7710. * @param {Node<vec3>} normal - The normal.
  7711. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  7712. * @return {Node<vec3>} The transformed normal.
  7713. */
  7714. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  7715. const m = mat3( matrix );
  7716. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  7717. return m.mul( transformedNormal ).xyz;
  7718. } );
  7719. /**
  7720. * Transforms the given normal from local to view space.
  7721. *
  7722. * @function
  7723. * @param {Node<vec3>} normal - The normal.
  7724. * @param {NodeBuilder} builder - The current node builder.
  7725. * @return {Node<vec3>} The transformed normal.
  7726. */
  7727. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  7728. const modelNormalViewMatrix = builder.renderer.nodes.modelNormalViewMatrix;
  7729. if ( modelNormalViewMatrix !== null ) {
  7730. return modelNormalViewMatrix.transformDirection( normal );
  7731. }
  7732. //
  7733. const transformedNormal = modelNormalMatrix.mul( normal );
  7734. return cameraViewMatrix.transformDirection( transformedNormal );
  7735. } );
  7736. /** @module MaterialProperties **/
  7737. /**
  7738. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  7739. *
  7740. * @type {UniformNode<float>}
  7741. */
  7742. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onRenderUpdate( ( { material } ) => material.refractionRatio );
  7743. /** @module ReflectVector **/
  7744. /**
  7745. * The reflect vector in view space.
  7746. *
  7747. * @type {Node<vec3>}
  7748. */
  7749. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  7750. /**
  7751. * The refract vector in view space.
  7752. *
  7753. * @type {Node<vec3>}
  7754. */
  7755. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  7756. /**
  7757. * Used for sampling cube maps when using cube reflection mapping.
  7758. *
  7759. * @type {Node<vec3>}
  7760. */
  7761. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7762. /**
  7763. * Used for sampling cube maps when using cube refraction mapping.
  7764. *
  7765. * @type {Node<vec3>}
  7766. */
  7767. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  7768. /** @module CubeTextureNode **/
  7769. /**
  7770. * This type of uniform node represents a cube texture.
  7771. *
  7772. * @augments module:TextureNode~TextureNode
  7773. */
  7774. class CubeTextureNode extends TextureNode {
  7775. static get type() {
  7776. return 'CubeTextureNode';
  7777. }
  7778. /**
  7779. * Constructs a new cube texture node.
  7780. *
  7781. * @param {CubeTexture} value - The cube texture.
  7782. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7783. * @param {Node<int>?} [levelNode=null] - The level node.
  7784. * @param {Node<float>?} [biasNode=null] - The bias node.
  7785. */
  7786. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  7787. super( value, uvNode, levelNode, biasNode );
  7788. /**
  7789. * This flag can be used for type testing.
  7790. *
  7791. * @type {Boolean}
  7792. * @readonly
  7793. * @default true
  7794. */
  7795. this.isCubeTextureNode = true;
  7796. }
  7797. /**
  7798. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  7799. *
  7800. * @param {NodeBuilder} builder - The current node builder.
  7801. * @return {String} The input type.
  7802. */
  7803. getInputType( /*builder*/ ) {
  7804. return 'cubeTexture';
  7805. }
  7806. /**
  7807. * Returns a default uvs based on the mapping type of the cube texture.
  7808. *
  7809. * @return {Node<vec3>} The default uv attribute.
  7810. */
  7811. getDefaultUV() {
  7812. const texture = this.value;
  7813. if ( texture.mapping === CubeReflectionMapping ) {
  7814. return reflectVector;
  7815. } else if ( texture.mapping === CubeRefractionMapping ) {
  7816. return refractVector;
  7817. } else {
  7818. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  7819. return vec3( 0, 0, 0 );
  7820. }
  7821. }
  7822. /**
  7823. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  7824. * for cube textures. The uv transformation matrix is not applied to cube textures.
  7825. *
  7826. * @param {Boolean} value - The update toggle.
  7827. */
  7828. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  7829. /**
  7830. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  7831. * to modify the uv node for correct sampling.
  7832. *
  7833. * @param {NodeBuilder} builder - The current node builder.
  7834. * @param {Node} uvNode - The uv node to setup.
  7835. * @return {Node} The updated uv node.
  7836. */
  7837. setupUV( builder, uvNode ) {
  7838. const texture = this.value;
  7839. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  7840. return vec3( uvNode.x.negate(), uvNode.yz );
  7841. } else {
  7842. return uvNode;
  7843. }
  7844. }
  7845. /**
  7846. * Generates the uv code snippet.
  7847. *
  7848. * @param {NodeBuilder} builder - The current node builder.
  7849. * @param {Node} cubeUV - The uv node to generate code for.
  7850. * @return {String} The generated code snippet.
  7851. */
  7852. generateUV( builder, cubeUV ) {
  7853. return cubeUV.build( builder, 'vec3' );
  7854. }
  7855. }
  7856. /**
  7857. * TSL function for creating a cube texture node.
  7858. *
  7859. * @function
  7860. * @param {CubeTexture} value - The cube texture.
  7861. * @param {Node<vec3>?} [uvNode=null] - The uv node.
  7862. * @param {Node<int>?} [levelNode=null] - The level node.
  7863. * @param {Node<float>?} [biasNode=null] - The bias node.
  7864. * @returns {CubeTextureNode}
  7865. */
  7866. const cubeTexture = /*@__PURE__*/ nodeProxy( CubeTextureNode );
  7867. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  7868. /** @module ReferenceNode **/
  7869. /**
  7870. * This class is only relevant if the referenced property is array-like.
  7871. * In this case, `ReferenceElementNode` allows to refer to a specific
  7872. * element inside the data structure via an index.
  7873. *
  7874. * @augments ArrayElementNode
  7875. */
  7876. class ReferenceElementNode extends ArrayElementNode {
  7877. static get type() {
  7878. return 'ReferenceElementNode';
  7879. }
  7880. /**
  7881. * Constructs a new reference element node.
  7882. *
  7883. * @param {ReferenceNode?} referenceNode - The reference node.
  7884. * @param {Node} indexNode - The index node that defines the element access.
  7885. */
  7886. constructor( referenceNode, indexNode ) {
  7887. super( referenceNode, indexNode );
  7888. /**
  7889. * Similar to {@link module:ReferenceNode~ReferenceNode#reference}, an additional
  7890. * property references to the current node.
  7891. *
  7892. * @type {ReferenceNode?}
  7893. * @default null
  7894. */
  7895. this.referenceNode = referenceNode;
  7896. /**
  7897. * This flag can be used for type testing.
  7898. *
  7899. * @type {Boolean}
  7900. * @readonly
  7901. * @default true
  7902. */
  7903. this.isReferenceElementNode = true;
  7904. }
  7905. /**
  7906. * This method is overwritten since the node type is inferred from
  7907. * the uniform type of the reference node.
  7908. *
  7909. * @return {String} The node type.
  7910. */
  7911. getNodeType() {
  7912. return this.referenceNode.uniformType;
  7913. }
  7914. generate( builder ) {
  7915. const snippet = super.generate( builder );
  7916. const arrayType = this.referenceNode.getNodeType();
  7917. const elementType = this.getNodeType();
  7918. return builder.format( snippet, arrayType, elementType );
  7919. }
  7920. }
  7921. /**
  7922. * This type of node establishes a reference to a property of another object.
  7923. * In this way, the value of the node is automatically linked to the value of
  7924. * referenced object. Reference nodes internally represent the linked value
  7925. * as a uniform.
  7926. *
  7927. * @augments Node
  7928. */
  7929. class ReferenceNode extends Node {
  7930. static get type() {
  7931. return 'ReferenceNode';
  7932. }
  7933. /**
  7934. * Constructs a new reference node.
  7935. *
  7936. * @param {String} property - The name of the property the node refers to.
  7937. * @param {String} uniformType - The uniform type that should be used to represent the property value.
  7938. * @param {Object?} [object=null] - The object the property belongs to.
  7939. * @param {Number?} [count=null] - When the linked property is an array-like, this parameter defines its length.
  7940. */
  7941. constructor( property, uniformType, object = null, count = null ) {
  7942. super();
  7943. /**
  7944. * The name of the property the node refers to.
  7945. *
  7946. * @type {String}
  7947. */
  7948. this.property = property;
  7949. /**
  7950. * The uniform type that should be used to represent the property value.
  7951. *
  7952. * @type {String}
  7953. */
  7954. this.uniformType = uniformType;
  7955. /**
  7956. * The object the property belongs to.
  7957. *
  7958. * @type {Object?}
  7959. * @default null
  7960. */
  7961. this.object = object;
  7962. /**
  7963. * When the linked property is an array, this parameter defines its length.
  7964. *
  7965. * @type {Number?}
  7966. * @default null
  7967. */
  7968. this.count = count;
  7969. /**
  7970. * The property name might have dots so nested properties can be referred.
  7971. * The hierarchy of the names is stored inside this array.
  7972. *
  7973. * @type {Array<String>}
  7974. */
  7975. this.properties = property.split( '.' );
  7976. /**
  7977. * Points to the current referred object. This property exists next to {@link module:ReferenceNode~ReferenceNode#object}
  7978. * since the final reference might be updated from calling code.
  7979. *
  7980. * @type {Object?}
  7981. * @default null
  7982. */
  7983. this.reference = object;
  7984. /**
  7985. * The uniform node that holds the value of the reference node.
  7986. *
  7987. * @type {UniformNode}
  7988. * @default null
  7989. */
  7990. this.node = null;
  7991. /**
  7992. * The uniform group of the internal uniform.
  7993. *
  7994. * @type {UniformGroupNode}
  7995. * @default null
  7996. */
  7997. this.group = null;
  7998. /**
  7999. * An optional label of the internal uniform node.
  8000. *
  8001. * @type {String?}
  8002. * @default null
  8003. */
  8004. this.name = null;
  8005. /**
  8006. * Overwritten since reference nodes are updated per object.
  8007. *
  8008. * @type {String}
  8009. * @default 'object'
  8010. */
  8011. this.updateType = NodeUpdateType.OBJECT;
  8012. }
  8013. /**
  8014. * When the referred property is array-like, this method can be used
  8015. * to access elements via an index node.
  8016. *
  8017. * @param {IndexNode} indexNode - indexNode.
  8018. * @return {ReferenceElementNode} A reference to an element.
  8019. */
  8020. element( indexNode ) {
  8021. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  8022. }
  8023. /**
  8024. * Sets the uniform group for this reference node.
  8025. *
  8026. * @param {UniformGroupNode} group - The uniform group to set.
  8027. * @return {ReferenceNode} A reference to this node.
  8028. */
  8029. setGroup( group ) {
  8030. this.group = group;
  8031. return this;
  8032. }
  8033. /**
  8034. * Sets the label for the internal uniform.
  8035. *
  8036. * @param {String} name - The label to set.
  8037. * @return {ReferenceNode} A reference to this node.
  8038. */
  8039. label( name ) {
  8040. this.name = name;
  8041. return this;
  8042. }
  8043. /**
  8044. * Sets the node type which automatically defines the internal
  8045. * uniform type.
  8046. *
  8047. * @param {String} uniformType - The type to set.
  8048. */
  8049. setNodeType( uniformType ) {
  8050. let node = null;
  8051. if ( this.count !== null ) {
  8052. node = buffer( null, uniformType, this.count );
  8053. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  8054. node = uniformArray( null, uniformType );
  8055. } else if ( uniformType === 'texture' ) {
  8056. node = texture( null );
  8057. } else if ( uniformType === 'cubeTexture' ) {
  8058. node = cubeTexture( null );
  8059. } else {
  8060. node = uniform( null, uniformType );
  8061. }
  8062. if ( this.group !== null ) {
  8063. node.setGroup( this.group );
  8064. }
  8065. if ( this.name !== null ) node.label( this.name );
  8066. this.node = node.getSelf();
  8067. }
  8068. /**
  8069. * This method is overwritten since the node type is inferred from
  8070. * the type of the reference node.
  8071. *
  8072. * @param {NodeBuilder} builder - The current node builder.
  8073. * @return {String} The node type.
  8074. */
  8075. getNodeType( builder ) {
  8076. if ( this.node === null ) {
  8077. this.updateReference( builder );
  8078. this.updateValue();
  8079. }
  8080. return this.node.getNodeType( builder );
  8081. }
  8082. /**
  8083. * Returns the property value from the given referred object.
  8084. *
  8085. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  8086. * @return {Any} The value.
  8087. */
  8088. getValueFromReference( object = this.reference ) {
  8089. const { properties } = this;
  8090. let value = object[ properties[ 0 ] ];
  8091. for ( let i = 1; i < properties.length; i ++ ) {
  8092. value = value[ properties[ i ] ];
  8093. }
  8094. return value;
  8095. }
  8096. /**
  8097. * Allows to update the reference based on the given state. The state is only
  8098. * evaluated {@link module:ReferenceNode~ReferenceNode#object} is not set.
  8099. *
  8100. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8101. * @return {Object} The updated reference.
  8102. */
  8103. updateReference( state ) {
  8104. this.reference = this.object !== null ? this.object : state.object;
  8105. return this.reference;
  8106. }
  8107. /**
  8108. * The output of the reference node is the internal uniform node.
  8109. *
  8110. * @param {NodeBuilder} builder - The current node builder.
  8111. * @return {UniformNode} The output node.
  8112. */
  8113. setup( /* builder */ ) {
  8114. this.updateValue();
  8115. return this.node;
  8116. }
  8117. /**
  8118. * Overwritten to to update the internal uniform value.
  8119. *
  8120. * @param {NodeFrame} frame - A reference to the current node frame.
  8121. */
  8122. update( /*frame*/ ) {
  8123. this.updateValue();
  8124. }
  8125. /**
  8126. * Retrieves the value from the referred object property and uses it
  8127. * to updated the internal uniform.
  8128. */
  8129. updateValue() {
  8130. if ( this.node === null ) this.setNodeType( this.uniformType );
  8131. const value = this.getValueFromReference();
  8132. if ( Array.isArray( value ) ) {
  8133. this.node.array = value;
  8134. } else {
  8135. this.node.value = value;
  8136. }
  8137. }
  8138. }
  8139. /**
  8140. * TSL function for creating a reference node.
  8141. *
  8142. * @function
  8143. * @param {String} name - The name of the property the node refers to.
  8144. * @param {String} type - The uniform type that should be used to represent the property value.
  8145. * @param {Object} object - The object the property belongs to.
  8146. * @returns {ReferenceNode}
  8147. */
  8148. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  8149. /**
  8150. * TSL function for creating a reference node. Use this function if you want need a reference
  8151. * to an array-like property that should be represented as a uniform buffer.
  8152. *
  8153. * @function
  8154. * @param {String} name - The name of the property the node refers to.
  8155. * @param {String} type - The uniform type that should be used to represent the property value.
  8156. * @param {Number} count - The number of value inside the array-like object.
  8157. * @param {Object} object - An array-like object the property belongs to.
  8158. * @returns {ReferenceNode}
  8159. */
  8160. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  8161. /** @module MaterialReferenceNode **/
  8162. /**
  8163. * This node is a special type of reference node which is intended
  8164. * for linking material properties with node values.
  8165. * ```js
  8166. * const opacityNode = materialReference( 'opacity', 'float', material );
  8167. * ```
  8168. * When changing `material.opacity`, the node value of `opacityNode` will
  8169. * automatically be updated.
  8170. *
  8171. * @augments module:ReferenceNode~ReferenceNode
  8172. */
  8173. class MaterialReferenceNode extends ReferenceNode {
  8174. static get type() {
  8175. return 'MaterialReferenceNode';
  8176. }
  8177. /**
  8178. * Constructs a new material reference node.
  8179. *
  8180. * @param {String} property - The name of the property the node refers to.
  8181. * @param {String} inputType - The uniform type that should be used to represent the property value.
  8182. * @param {Material?} [material=null] - The material the property belongs to. When no material is set,
  8183. * the node refers to the material of the current rendered object.
  8184. */
  8185. constructor( property, inputType, material = null ) {
  8186. super( property, inputType, material );
  8187. /**
  8188. * The material the property belongs to. When no material is set,
  8189. * the node refers to the material of the current rendered object.
  8190. *
  8191. * @type {Material?}
  8192. * @default null
  8193. */
  8194. this.material = material;
  8195. /**
  8196. * This flag can be used for type testing.
  8197. *
  8198. * @type {Boolean}
  8199. * @readonly
  8200. * @default true
  8201. */
  8202. this.isMaterialReferenceNode = true;
  8203. }
  8204. /**
  8205. * Updates the reference based on the given state. The state is only evaluated
  8206. * {@link module:MaterialReferenceNode~MaterialReferenceNode#material} is not set.
  8207. *
  8208. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  8209. * @return {Object} The updated reference.
  8210. */
  8211. updateReference( state ) {
  8212. this.reference = this.material !== null ? this.material : state.material;
  8213. return this.reference;
  8214. }
  8215. }
  8216. /**
  8217. * TSL function for creating a material reference node.
  8218. *
  8219. * @function
  8220. * @param {String} name - The name of the property the node refers to.
  8221. * @param {String} type - The uniform type that should be used to represent the property value.
  8222. * @param {Material?} [material=null] - The material the property belongs to.
  8223. * When no material is set, the node refers to the material of the current rendered object.
  8224. * @returns {MaterialReferenceNode}
  8225. */
  8226. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  8227. /** @module Tangent **/
  8228. /**
  8229. * TSL object that represents the tangent attribute of the current rendered object.
  8230. *
  8231. * @type {Node<vec4>}
  8232. */
  8233. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  8234. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  8235. builder.geometry.computeTangents();
  8236. }
  8237. return attribute( 'tangent', 'vec4' );
  8238. } )();
  8239. /**
  8240. * TSL object that represents the vertex tangent in local space of the current rendered object.
  8241. *
  8242. * @type {Node<vec3>}
  8243. */
  8244. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  8245. /**
  8246. * TSL object that represents the vertex tangent in view space of the current rendered object.
  8247. *
  8248. * @type {Node<vec3>}
  8249. */
  8250. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.varying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  8251. /**
  8252. * TSL object that represents the vertex tangent in world space of the current rendered object.
  8253. *
  8254. * @type {Node<vec3>}
  8255. */
  8256. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).varying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  8257. /**
  8258. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  8259. *
  8260. * @type {Node<vec3>}
  8261. */
  8262. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  8263. /**
  8264. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  8265. *
  8266. * @type {Node<vec3>}
  8267. */
  8268. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  8269. /** @module Bitangent **/
  8270. const getBitangent = ( crossNormalTangent ) => crossNormalTangent.mul( tangentGeometry.w ).xyz;
  8271. /**
  8272. * TSL object that represents the bitangent attribute of the current rendered object.
  8273. *
  8274. * @type {Node<vec3>}
  8275. */
  8276. const bitangentGeometry = /*@__PURE__*/ varying( getBitangent( normalGeometry.cross( tangentGeometry ) ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  8277. /**
  8278. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  8279. *
  8280. * @type {Node<vec3>}
  8281. */
  8282. const bitangentLocal = /*@__PURE__*/ varying( getBitangent( normalLocal.cross( tangentLocal ) ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  8283. /**
  8284. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  8285. *
  8286. * @type {Node<vec4>}
  8287. */
  8288. const bitangentView = /*@__PURE__*/ varying( getBitangent( normalView.cross( tangentView ) ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  8289. /**
  8290. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  8291. *
  8292. * @type {Node<vec4>}
  8293. */
  8294. const bitangentWorld = /*@__PURE__*/ varying( getBitangent( normalWorld.cross( tangentWorld ) ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  8295. /**
  8296. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  8297. *
  8298. * @type {Node<vec4>}
  8299. */
  8300. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ) ).normalize().toVar( 'transformedBitangentView' );
  8301. /**
  8302. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  8303. *
  8304. * @type {Node<vec4>}
  8305. */
  8306. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  8307. /** @module AccessorsUtils **/
  8308. /**
  8309. * TSL object that represents the TBN matrix in view space.
  8310. *
  8311. * @type {Node<mat3>}
  8312. */
  8313. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  8314. /**
  8315. * TSL object that represents the parallax direction.
  8316. *
  8317. * @type {Node<mat3>}
  8318. */
  8319. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  8320. /**
  8321. * TSL function for computing parallax uv coordinates.
  8322. *
  8323. * @function
  8324. * @param {Node<vec2>} uv - A uv node.
  8325. * @param {Node<vec2>} scale - A scale node.
  8326. * @returns {Node<vec2>} Parallax uv coordinates.
  8327. */
  8328. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  8329. /**
  8330. * TSL function for computing bent normals.
  8331. *
  8332. * @function
  8333. * @returns {Node<vec3>} Bent normals.
  8334. */
  8335. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  8336. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  8337. let bentNormal = anisotropyB.cross( positionViewDirection );
  8338. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  8339. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  8340. return bentNormal;
  8341. } )();
  8342. /** @module NormalMapNode **/
  8343. // Normal Mapping Without Precomputed Tangents
  8344. // http://www.thetenthplanet.de/archives/1180
  8345. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  8346. const { eye_pos, surf_norm, mapN, uv } = inputs;
  8347. const q0 = eye_pos.dFdx();
  8348. const q1 = eye_pos.dFdy();
  8349. const st0 = uv.dFdx();
  8350. const st1 = uv.dFdy();
  8351. const N = surf_norm; // normalized
  8352. const q1perp = q1.cross( N );
  8353. const q0perp = N.cross( q0 );
  8354. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  8355. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  8356. const det = T.dot( T ).max( B.dot( B ) );
  8357. const scale = faceDirection.mul( det.inverseSqrt() );
  8358. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  8359. } );
  8360. /**
  8361. * This class can be used for applying normals maps to materials.
  8362. *
  8363. * ```js
  8364. * material.normalNode = normalMap( texture( normalTex ) );
  8365. * ```
  8366. *
  8367. * @augments TempNode
  8368. */
  8369. class NormalMapNode extends TempNode {
  8370. static get type() {
  8371. return 'NormalMapNode';
  8372. }
  8373. /**
  8374. * Constructs a new normal map node.
  8375. *
  8376. * @param {Node<vec3>} node - Represents the normal map data.
  8377. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8378. */
  8379. constructor( node, scaleNode = null ) {
  8380. super( 'vec3' );
  8381. /**
  8382. * Represents the normal map data.
  8383. *
  8384. * @type {Node<vec3>}
  8385. */
  8386. this.node = node;
  8387. /**
  8388. * Controls the intensity of the effect.
  8389. *
  8390. * @type {Node<vec2>?}
  8391. * @default null
  8392. */
  8393. this.scaleNode = scaleNode;
  8394. /**
  8395. * The normal map type.
  8396. *
  8397. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  8398. * @default TangentSpaceNormalMap
  8399. */
  8400. this.normalMapType = TangentSpaceNormalMap;
  8401. }
  8402. setup( builder ) {
  8403. const { normalMapType, scaleNode } = this;
  8404. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  8405. if ( scaleNode !== null ) {
  8406. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  8407. }
  8408. let outputNode = null;
  8409. if ( normalMapType === ObjectSpaceNormalMap ) {
  8410. outputNode = transformNormalToView( normalMap );
  8411. } else if ( normalMapType === TangentSpaceNormalMap ) {
  8412. const tangent = builder.hasGeometryAttribute( 'tangent' );
  8413. if ( tangent === true ) {
  8414. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  8415. } else {
  8416. outputNode = perturbNormal2Arb( {
  8417. eye_pos: positionView,
  8418. surf_norm: normalView,
  8419. mapN: normalMap,
  8420. uv: uv()
  8421. } );
  8422. }
  8423. }
  8424. return outputNode;
  8425. }
  8426. }
  8427. /**
  8428. * TSL function for creating a normal map node.
  8429. *
  8430. * @function
  8431. * @param {Node<vec3>} node - Represents the normal map data.
  8432. * @param {Node<vec2>?} [scaleNode=null] - Controls the intensity of the effect.
  8433. * @returns {NormalMapNode}
  8434. */
  8435. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode );
  8436. /** @module BumpMapNode **/
  8437. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  8438. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  8439. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  8440. // It's used to preserve the same TextureNode instance
  8441. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  8442. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  8443. return vec2(
  8444. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  8445. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  8446. ).mul( bumpScale );
  8447. } );
  8448. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8449. const perturbNormalArb = Fn( ( inputs ) => {
  8450. const { surf_pos, surf_norm, dHdxy } = inputs;
  8451. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  8452. const vSigmaX = surf_pos.dFdx().normalize();
  8453. const vSigmaY = surf_pos.dFdy().normalize();
  8454. const vN = surf_norm; // normalized
  8455. const R1 = vSigmaY.cross( vN );
  8456. const R2 = vN.cross( vSigmaX );
  8457. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  8458. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  8459. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  8460. } );
  8461. /**
  8462. * This class can be used for applying bump maps to materials.
  8463. *
  8464. * ```js
  8465. * material.normalNode = bumpMap( texture( bumpTex ) );
  8466. * ```
  8467. *
  8468. * @augments TempNode
  8469. */
  8470. class BumpMapNode extends TempNode {
  8471. static get type() {
  8472. return 'BumpMapNode';
  8473. }
  8474. /**
  8475. * Constructs a new bump map node.
  8476. *
  8477. * @param {Node<float>} textureNode - Represents the bump map data.
  8478. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8479. */
  8480. constructor( textureNode, scaleNode = null ) {
  8481. super( 'vec3' );
  8482. /**
  8483. * Represents the bump map data.
  8484. *
  8485. * @type {Node<float>}
  8486. */
  8487. this.textureNode = textureNode;
  8488. /**
  8489. * Controls the intensity of the bump effect.
  8490. *
  8491. * @type {Node<float>?}
  8492. * @default null
  8493. */
  8494. this.scaleNode = scaleNode;
  8495. }
  8496. setup() {
  8497. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  8498. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  8499. return perturbNormalArb( {
  8500. surf_pos: positionView,
  8501. surf_norm: normalView,
  8502. dHdxy
  8503. } );
  8504. }
  8505. }
  8506. /**
  8507. * TSL function for creating a bump map node.
  8508. *
  8509. * @function
  8510. * @param {Node<float>} textureNode - Represents the bump map data.
  8511. * @param {Node<float>?} [scaleNode=null] - Controls the intensity of the bump effect.
  8512. * @returns {BumpMapNode}
  8513. */
  8514. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode );
  8515. /** @module MaterialNode **/
  8516. const _propertyCache = new Map();
  8517. /**
  8518. * This class should simplify the node access to material properties.
  8519. * It internal uses reference nodes to make sure changes to material
  8520. * properties are automatically reflected to predefined TSL objects
  8521. * like e.g. `materialColor`.
  8522. *
  8523. * @augments Node
  8524. */
  8525. class MaterialNode extends Node {
  8526. static get type() {
  8527. return 'MaterialNode';
  8528. }
  8529. /**
  8530. * Constructs a new material node.
  8531. *
  8532. * @param {String} scope - The scope defines what kind of material property is referred by the node.
  8533. */
  8534. constructor( scope ) {
  8535. super();
  8536. /**
  8537. * The scope defines what material property is referred by the node.
  8538. *
  8539. * @type {String}
  8540. */
  8541. this.scope = scope;
  8542. }
  8543. /**
  8544. * Returns a cached reference node for the given property and type.
  8545. *
  8546. * @param {String} property - The name of the material property.
  8547. * @param {String} type - The uniform type of the property.
  8548. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8549. */
  8550. getCache( property, type ) {
  8551. let node = _propertyCache.get( property );
  8552. if ( node === undefined ) {
  8553. node = materialReference( property, type );
  8554. _propertyCache.set( property, node );
  8555. }
  8556. return node;
  8557. }
  8558. /**
  8559. * Returns a float-typed material reference node for the given property name.
  8560. *
  8561. * @param {String} property - The name of the material property.
  8562. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  8563. */
  8564. getFloat( property ) {
  8565. return this.getCache( property, 'float' );
  8566. }
  8567. /**
  8568. * Returns a color-typed material reference node for the given property name.
  8569. *
  8570. * @param {String} property - The name of the material property.
  8571. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  8572. */
  8573. getColor( property ) {
  8574. return this.getCache( property, 'color' );
  8575. }
  8576. /**
  8577. * Returns a texture-typed material reference node for the given property name.
  8578. *
  8579. * @param {String} property - The name of the material property.
  8580. * @return {MaterialReferenceNode} A material reference node representing the property access.
  8581. */
  8582. getTexture( property ) {
  8583. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  8584. }
  8585. /**
  8586. * The node setup is done depending on the selected scope. Multiple material properties
  8587. * might be grouped into a single node composition if they logically belong together.
  8588. *
  8589. * @param {NodeBuilder} builder - The current node builder.
  8590. * @return {Node} The node representing the selected scope.
  8591. */
  8592. setup( builder ) {
  8593. const material = builder.context.material;
  8594. const scope = this.scope;
  8595. let node = null;
  8596. if ( scope === MaterialNode.COLOR ) {
  8597. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  8598. if ( material.map && material.map.isTexture === true ) {
  8599. node = colorNode.mul( this.getTexture( 'map' ) );
  8600. } else {
  8601. node = colorNode;
  8602. }
  8603. } else if ( scope === MaterialNode.OPACITY ) {
  8604. const opacityNode = this.getFloat( scope );
  8605. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  8606. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  8607. } else {
  8608. node = opacityNode;
  8609. }
  8610. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  8611. if ( material.specularMap && material.specularMap.isTexture === true ) {
  8612. node = this.getTexture( 'specular' ).r;
  8613. } else {
  8614. node = float( 1 );
  8615. }
  8616. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  8617. const specularIntensityNode = this.getFloat( scope );
  8618. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  8619. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  8620. } else {
  8621. node = specularIntensityNode;
  8622. }
  8623. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  8624. const specularColorNode = this.getColor( scope );
  8625. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  8626. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  8627. } else {
  8628. node = specularColorNode;
  8629. }
  8630. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  8631. const roughnessNode = this.getFloat( scope );
  8632. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  8633. node = roughnessNode.mul( this.getTexture( scope ).g );
  8634. } else {
  8635. node = roughnessNode;
  8636. }
  8637. } else if ( scope === MaterialNode.METALNESS ) {
  8638. const metalnessNode = this.getFloat( scope );
  8639. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  8640. node = metalnessNode.mul( this.getTexture( scope ).b );
  8641. } else {
  8642. node = metalnessNode;
  8643. }
  8644. } else if ( scope === MaterialNode.EMISSIVE ) {
  8645. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  8646. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  8647. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  8648. node = emissiveNode.mul( this.getTexture( scope ) );
  8649. } else {
  8650. node = emissiveNode;
  8651. }
  8652. } else if ( scope === MaterialNode.NORMAL ) {
  8653. if ( material.normalMap ) {
  8654. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  8655. node.normalMapType = material.normalMapType;
  8656. } else if ( material.bumpMap ) {
  8657. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  8658. } else {
  8659. node = normalView;
  8660. }
  8661. } else if ( scope === MaterialNode.CLEARCOAT ) {
  8662. const clearcoatNode = this.getFloat( scope );
  8663. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  8664. node = clearcoatNode.mul( this.getTexture( scope ).r );
  8665. } else {
  8666. node = clearcoatNode;
  8667. }
  8668. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  8669. const clearcoatRoughnessNode = this.getFloat( scope );
  8670. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  8671. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  8672. } else {
  8673. node = clearcoatRoughnessNode;
  8674. }
  8675. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  8676. if ( material.clearcoatNormalMap ) {
  8677. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  8678. } else {
  8679. node = normalView;
  8680. }
  8681. } else if ( scope === MaterialNode.SHEEN ) {
  8682. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  8683. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  8684. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  8685. } else {
  8686. node = sheenNode;
  8687. }
  8688. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  8689. const sheenRoughnessNode = this.getFloat( scope );
  8690. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  8691. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  8692. } else {
  8693. node = sheenRoughnessNode;
  8694. }
  8695. node = node.clamp( 0.07, 1.0 );
  8696. } else if ( scope === MaterialNode.ANISOTROPY ) {
  8697. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  8698. const anisotropyPolar = this.getTexture( scope );
  8699. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  8700. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  8701. } else {
  8702. node = materialAnisotropyVector;
  8703. }
  8704. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  8705. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  8706. if ( material.iridescenceThicknessMap ) {
  8707. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  8708. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  8709. } else {
  8710. node = iridescenceThicknessMaximum;
  8711. }
  8712. } else if ( scope === MaterialNode.TRANSMISSION ) {
  8713. const transmissionNode = this.getFloat( scope );
  8714. if ( material.transmissionMap ) {
  8715. node = transmissionNode.mul( this.getTexture( scope ).r );
  8716. } else {
  8717. node = transmissionNode;
  8718. }
  8719. } else if ( scope === MaterialNode.THICKNESS ) {
  8720. const thicknessNode = this.getFloat( scope );
  8721. if ( material.thicknessMap ) {
  8722. node = thicknessNode.mul( this.getTexture( scope ).g );
  8723. } else {
  8724. node = thicknessNode;
  8725. }
  8726. } else if ( scope === MaterialNode.IOR ) {
  8727. node = this.getFloat( scope );
  8728. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  8729. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  8730. } else if ( scope === MaterialNode.AO ) {
  8731. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  8732. } else {
  8733. const outputType = this.getNodeType( builder );
  8734. node = this.getCache( scope, outputType );
  8735. }
  8736. return node;
  8737. }
  8738. }
  8739. MaterialNode.ALPHA_TEST = 'alphaTest';
  8740. MaterialNode.COLOR = 'color';
  8741. MaterialNode.OPACITY = 'opacity';
  8742. MaterialNode.SHININESS = 'shininess';
  8743. MaterialNode.SPECULAR = 'specular';
  8744. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  8745. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  8746. MaterialNode.SPECULAR_COLOR = 'specularColor';
  8747. MaterialNode.REFLECTIVITY = 'reflectivity';
  8748. MaterialNode.ROUGHNESS = 'roughness';
  8749. MaterialNode.METALNESS = 'metalness';
  8750. MaterialNode.NORMAL = 'normal';
  8751. MaterialNode.CLEARCOAT = 'clearcoat';
  8752. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  8753. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  8754. MaterialNode.EMISSIVE = 'emissive';
  8755. MaterialNode.ROTATION = 'rotation';
  8756. MaterialNode.SHEEN = 'sheen';
  8757. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  8758. MaterialNode.ANISOTROPY = 'anisotropy';
  8759. MaterialNode.IRIDESCENCE = 'iridescence';
  8760. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  8761. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  8762. MaterialNode.IOR = 'ior';
  8763. MaterialNode.TRANSMISSION = 'transmission';
  8764. MaterialNode.THICKNESS = 'thickness';
  8765. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  8766. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  8767. MaterialNode.LINE_SCALE = 'scale';
  8768. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  8769. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  8770. MaterialNode.LINE_WIDTH = 'linewidth';
  8771. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  8772. MaterialNode.POINT_SIZE = 'size';
  8773. MaterialNode.DISPERSION = 'dispersion';
  8774. MaterialNode.LIGHT_MAP = 'light';
  8775. MaterialNode.AO = 'ao';
  8776. /**
  8777. * TSL object that represents alpha test of the current material.
  8778. *
  8779. * @type {Node<float>}
  8780. */
  8781. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  8782. /**
  8783. * TSL object that represents the diffuse color of the current material.
  8784. * The value is composed via `color` * `map`.
  8785. *
  8786. * @type {Node<vec3>}
  8787. */
  8788. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  8789. /**
  8790. * TSL object that represents the shininess of the current material.
  8791. *
  8792. * @type {Node<float>}
  8793. */
  8794. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  8795. /**
  8796. * TSL object that represents the emissive color of the current material.
  8797. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  8798. *
  8799. * @type {Node<vec3>}
  8800. */
  8801. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  8802. /**
  8803. * TSL object that represents the opacity of the current material.
  8804. * The value is composed via `opacity` * `alphaMap`.
  8805. *
  8806. * @type {Node<float>}
  8807. */
  8808. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  8809. /**
  8810. * TSL object that represents the specular of the current material.
  8811. *
  8812. * @type {Node<vec3>}
  8813. */
  8814. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  8815. /**
  8816. * TSL object that represents the specular intensity of the current material.
  8817. * The value is composed via `specularIntensity` * `specularMap.a`.
  8818. *
  8819. * @type {Node<float>}
  8820. */
  8821. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  8822. /**
  8823. * TSL object that represents the specular color of the current material.
  8824. * The value is composed via `specularColor` * `specularMap.rgb`.
  8825. *
  8826. * @type {Node<vec3>}
  8827. */
  8828. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  8829. /**
  8830. * TSL object that represents the specular strength of the current material.
  8831. * The value is composed via `specularMap.r`.
  8832. *
  8833. * @type {Node<float>}
  8834. */
  8835. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  8836. /**
  8837. * TSL object that represents the reflectivity of the current material.
  8838. *
  8839. * @type {Node<float>}
  8840. */
  8841. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  8842. /**
  8843. * TSL object that represents the roughness of the current material.
  8844. * The value is composed via `roughness` * `roughnessMap.g`.
  8845. *
  8846. * @type {Node<float>}
  8847. */
  8848. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  8849. /**
  8850. * TSL object that represents the metalness of the current material.
  8851. * The value is composed via `metalness` * `metalnessMap.b`.
  8852. *
  8853. * @type {Node<float>}
  8854. */
  8855. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  8856. /**
  8857. * TSL object that represents the normal of the current material.
  8858. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  8859. *
  8860. * @type {Node<vec3>}
  8861. */
  8862. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  8863. /**
  8864. * TSL object that represents the clearcoat of the current material.
  8865. * The value is composed via `clearcoat` * `clearcoatMap.r`
  8866. *
  8867. * @type {Node<float>}
  8868. */
  8869. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  8870. /**
  8871. * TSL object that represents the clearcoat roughness of the current material.
  8872. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  8873. *
  8874. * @type {Node<float>}
  8875. */
  8876. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  8877. /**
  8878. * TSL object that represents the clearcoat normal of the current material.
  8879. * The value will be either `clearcoatNormalMap` or `normalView`.
  8880. *
  8881. * @type {Node<vec3>}
  8882. */
  8883. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  8884. /**
  8885. * TSL object that represents the rotation of the current sprite material.
  8886. *
  8887. * @type {Node<float>}
  8888. */
  8889. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  8890. /**
  8891. * TSL object that represents the sheen color of the current material.
  8892. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  8893. *
  8894. * @type {Node<vec3>}
  8895. */
  8896. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  8897. /**
  8898. * TSL object that represents the sheen roughness of the current material.
  8899. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  8900. *
  8901. * @type {Node<float>}
  8902. */
  8903. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  8904. /**
  8905. * TSL object that represents the anisotropy of the current material.
  8906. *
  8907. * @type {Node<vec2>}
  8908. */
  8909. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  8910. /**
  8911. * TSL object that represents the iridescence of the current material.
  8912. *
  8913. * @type {Node<float>}
  8914. */
  8915. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  8916. /**
  8917. * TSL object that represents the iridescence IOR of the current material.
  8918. *
  8919. * @type {Node<float>}
  8920. */
  8921. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  8922. /**
  8923. * TSL object that represents the iridescence thickness of the current material.
  8924. *
  8925. * @type {Node<float>}
  8926. */
  8927. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  8928. /**
  8929. * TSL object that represents the transmission of the current material.
  8930. * The value is composed via `transmission` * `transmissionMap.r`.
  8931. *
  8932. * @type {Node<float>}
  8933. */
  8934. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  8935. /**
  8936. * TSL object that represents the thickness of the current material.
  8937. * The value is composed via `thickness` * `thicknessMap.g`.
  8938. *
  8939. * @type {Node<float>}
  8940. */
  8941. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  8942. /**
  8943. * TSL object that represents the IOR of the current material.
  8944. *
  8945. * @type {Node<float>}
  8946. */
  8947. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  8948. /**
  8949. * TSL object that represents the attenuation distance of the current material.
  8950. *
  8951. * @type {Node<float>}
  8952. */
  8953. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  8954. /**
  8955. * TSL object that represents the attenuation color of the current material.
  8956. *
  8957. * @type {Node<vec3>}
  8958. */
  8959. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  8960. /**
  8961. * TSL object that represents the scale of the current dashed line material.
  8962. *
  8963. * @type {Node<float>}
  8964. */
  8965. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  8966. /**
  8967. * TSL object that represents the dash size of the current dashed line material.
  8968. *
  8969. * @type {Node<float>}
  8970. */
  8971. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  8972. /**
  8973. * TSL object that represents the gap size of the current dashed line material.
  8974. *
  8975. * @type {Node<float>}
  8976. */
  8977. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  8978. /**
  8979. * TSL object that represents the line width of the current line material.
  8980. *
  8981. * @type {Node<float>}
  8982. */
  8983. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  8984. /**
  8985. * TSL object that represents the dash offset of the current line material.
  8986. *
  8987. * @type {Node<float>}
  8988. */
  8989. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  8990. /**
  8991. * TSL object that represents the point size of the current points material.
  8992. *
  8993. * @type {Node<float>}
  8994. */
  8995. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  8996. /**
  8997. * TSL object that represents the dispersion of the current material.
  8998. *
  8999. * @type {Node<float>}
  9000. */
  9001. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  9002. /**
  9003. * TSL object that represents the light map of the current material.
  9004. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  9005. *
  9006. * @type {Node<vec3>}
  9007. */
  9008. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  9009. /**
  9010. * TSL object that represents the ambient occlusion map of the current material.
  9011. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  9012. *
  9013. * @type {Node<float>}
  9014. */
  9015. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  9016. /**
  9017. * TSL object that represents the anisotropy vector of the current material.
  9018. *
  9019. * @type {Node<vec2>}
  9020. */
  9021. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  9022. return frame.material;
  9023. } ).onRenderUpdate( function ( { material } ) {
  9024. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  9025. } );
  9026. /** @module ModelViewProjectionNode **/
  9027. /**
  9028. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  9029. *
  9030. * @type {VaryingNode<vec4>}
  9031. */
  9032. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  9033. return builder.context.setupModelViewProjection();
  9034. }, 'vec4' ).once() )().varying( 'v_modelViewProjection' );
  9035. /** @module IndexNode **/
  9036. /**
  9037. * This class represents shader indices of different types. The following predefined node
  9038. * objects cover frequent use cases:
  9039. *
  9040. * - `vertexIndex`: The index of a vertex within a mesh.
  9041. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  9042. * - `drawIndex`: The index of a draw call.
  9043. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  9044. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  9045. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  9046. *
  9047. * @augments Node
  9048. */
  9049. class IndexNode extends Node {
  9050. static get type() {
  9051. return 'IndexNode';
  9052. }
  9053. /**
  9054. * Constructs a new index node.
  9055. *
  9056. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  9057. */
  9058. constructor( scope ) {
  9059. super( 'uint' );
  9060. /**
  9061. * The scope of the index node.
  9062. *
  9063. * @type {String}
  9064. */
  9065. this.scope = scope;
  9066. /**
  9067. * This flag can be used for type testing.
  9068. *
  9069. * @type {Boolean}
  9070. * @readonly
  9071. * @default true
  9072. */
  9073. this.isIndexNode = true;
  9074. }
  9075. generate( builder ) {
  9076. const nodeType = this.getNodeType( builder );
  9077. const scope = this.scope;
  9078. let propertyName;
  9079. if ( scope === IndexNode.VERTEX ) {
  9080. propertyName = builder.getVertexIndex();
  9081. } else if ( scope === IndexNode.INSTANCE ) {
  9082. propertyName = builder.getInstanceIndex();
  9083. } else if ( scope === IndexNode.DRAW ) {
  9084. propertyName = builder.getDrawIndex();
  9085. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  9086. propertyName = builder.getInvocationLocalIndex();
  9087. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  9088. propertyName = builder.getInvocationSubgroupIndex();
  9089. } else if ( scope === IndexNode.SUBGROUP ) {
  9090. propertyName = builder.getSubgroupIndex();
  9091. } else {
  9092. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  9093. }
  9094. let output;
  9095. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  9096. output = propertyName;
  9097. } else {
  9098. const nodeVarying = varying( this );
  9099. output = nodeVarying.build( builder, nodeType );
  9100. }
  9101. return output;
  9102. }
  9103. }
  9104. IndexNode.VERTEX = 'vertex';
  9105. IndexNode.INSTANCE = 'instance';
  9106. IndexNode.SUBGROUP = 'subgroup';
  9107. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  9108. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  9109. IndexNode.DRAW = 'draw';
  9110. /**
  9111. * TSL object that represents the index of a vertex within a mesh.
  9112. *
  9113. * @type {IndexNode}
  9114. */
  9115. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  9116. /**
  9117. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  9118. *
  9119. * @type {IndexNode}
  9120. */
  9121. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  9122. /**
  9123. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  9124. *
  9125. * @type {IndexNode}
  9126. */
  9127. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  9128. /**
  9129. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  9130. *
  9131. * @type {IndexNode}
  9132. */
  9133. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  9134. /**
  9135. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  9136. *
  9137. * @type {IndexNode}
  9138. */
  9139. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  9140. /**
  9141. * TSL object that represents the index of a draw call.
  9142. *
  9143. * @type {IndexNode}
  9144. */
  9145. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  9146. /** @module InstanceNode **/
  9147. /**
  9148. * This node implements the vertex shader logic which is required
  9149. * when rendering 3D objects via instancing. The code makes sure
  9150. * vertex positions, normals and colors can be modified via instanced
  9151. * data.
  9152. *
  9153. * @augments Node
  9154. */
  9155. class InstanceNode extends Node {
  9156. static get type() {
  9157. return 'InstanceNode';
  9158. }
  9159. /**
  9160. * Constructs a new instance node.
  9161. *
  9162. * @param {Number} count - The number of instances.
  9163. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9164. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9165. */
  9166. constructor( count, instanceMatrix, instanceColor ) {
  9167. super( 'void' );
  9168. /**
  9169. * The number of instances.
  9170. *
  9171. * @type {Number}
  9172. */
  9173. this.count = count;
  9174. /**
  9175. * Instanced buffer attribute representing the transformation of instances.
  9176. *
  9177. * @type {InstancedBufferAttribute}
  9178. */
  9179. this.instanceMatrix = instanceMatrix;
  9180. /**
  9181. * Instanced buffer attribute representing the color of instances.
  9182. *
  9183. * @type {InstancedBufferAttribute}
  9184. */
  9185. this.instanceColor = instanceColor;
  9186. /**
  9187. * The node that represents the instance matrix data.
  9188. *
  9189. * @type {Node}
  9190. */
  9191. this.instanceMatrixNode = null;
  9192. /**
  9193. * The node that represents the instance color data.
  9194. *
  9195. * @type {Node}
  9196. */
  9197. this.instanceColorNode = null;
  9198. /**
  9199. * The update type is set to `frame` since an update
  9200. * of instanced buffer data must be checked per frame.
  9201. *
  9202. * @type {String}
  9203. * @default 'frame'
  9204. */
  9205. this.updateType = NodeUpdateType.FRAME;
  9206. /**
  9207. * A reference to a buffer that is used by `instanceMatrixNode`.
  9208. *
  9209. * @type {InstancedInterleavedBuffer}
  9210. */
  9211. this.buffer = null;
  9212. /**
  9213. * A reference to a buffer that is used by `instanceColorNode`.
  9214. *
  9215. * @type {InstancedBufferAttribute}
  9216. */
  9217. this.bufferColor = null;
  9218. }
  9219. /**
  9220. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9221. * to predefined node variables for accumulation. That follows the same patterns
  9222. * like with morph and skinning nodes.
  9223. *
  9224. * @param {NodeBuilder} builder - The current node builder.
  9225. */
  9226. setup( builder ) {
  9227. const { count, instanceMatrix, instanceColor } = this;
  9228. let { instanceMatrixNode, instanceColorNode } = this;
  9229. if ( instanceMatrixNode === null ) {
  9230. // Both WebGPU and WebGL backends have UBO max limited to 64kb. Matrix count number bigger than 1000 ( 16 * 4 * 1000 = 64kb ) will fallback to attribute.
  9231. if ( count <= 1000 ) {
  9232. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  9233. } else {
  9234. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  9235. this.buffer = buffer;
  9236. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9237. const instanceBuffers = [
  9238. // F.Signature -> bufferAttribute( array, type, stride, offset )
  9239. bufferFn( buffer, 'vec4', 16, 0 ),
  9240. bufferFn( buffer, 'vec4', 16, 4 ),
  9241. bufferFn( buffer, 'vec4', 16, 8 ),
  9242. bufferFn( buffer, 'vec4', 16, 12 )
  9243. ];
  9244. instanceMatrixNode = mat4( ...instanceBuffers );
  9245. }
  9246. this.instanceMatrixNode = instanceMatrixNode;
  9247. }
  9248. if ( instanceColor && instanceColorNode === null ) {
  9249. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  9250. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  9251. this.bufferColor = buffer;
  9252. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  9253. this.instanceColorNode = instanceColorNode;
  9254. }
  9255. // POSITION
  9256. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  9257. positionLocal.assign( instancePosition );
  9258. // NORMAL
  9259. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9260. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  9261. // ASSIGNS
  9262. normalLocal.assign( instanceNormal );
  9263. }
  9264. // COLOR
  9265. if ( this.instanceColorNode !== null ) {
  9266. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  9267. }
  9268. }
  9269. /**
  9270. * Checks if the internal buffers required an update.
  9271. *
  9272. * @param {NodeFrame} frame - The current node frame.
  9273. */
  9274. update( /*frame*/ ) {
  9275. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  9276. this.buffer.version = this.instanceMatrix.version;
  9277. }
  9278. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  9279. this.bufferColor.version = this.instanceColor.version;
  9280. }
  9281. }
  9282. }
  9283. /**
  9284. * TSL function for creating an instance node.
  9285. *
  9286. * @function
  9287. * @param {Number} count - The number of instances.
  9288. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  9289. * @param {InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  9290. * @returns {InstanceNode}
  9291. */
  9292. const instance = /*@__PURE__*/ nodeProxy( InstanceNode );
  9293. /** @module InstancedMeshNode **/
  9294. /**
  9295. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  9296. * It allows an easier setup of the instance node.
  9297. *
  9298. * @augments module:InstanceNode~InstanceNode
  9299. */
  9300. class InstancedMeshNode extends InstanceNode {
  9301. static get type() {
  9302. return 'InstancedMeshNode';
  9303. }
  9304. /**
  9305. * Constructs a new instanced mesh node.
  9306. *
  9307. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  9308. */
  9309. constructor( instancedMesh ) {
  9310. const { count, instanceMatrix, instanceColor } = instancedMesh;
  9311. super( count, instanceMatrix, instanceColor );
  9312. /**
  9313. * A reference to the instanced mesh.
  9314. *
  9315. * @type {InstancedMesh}
  9316. */
  9317. this.instancedMesh = instancedMesh;
  9318. }
  9319. }
  9320. /**
  9321. * TSL function for creating an instanced mesh node.
  9322. *
  9323. * @function
  9324. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  9325. * @returns {InstancedMeshNode}
  9326. */
  9327. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode );
  9328. /** @module BatchNode **/
  9329. /**
  9330. * This node implements the vertex shader logic which is required
  9331. * when rendering 3D objects via batching. `BatchNode` must be used
  9332. * with instances of {@link BatchedMesh}.
  9333. *
  9334. * @augments Node
  9335. */
  9336. class BatchNode extends Node {
  9337. static get type() {
  9338. return 'BatchNode';
  9339. }
  9340. /**
  9341. * Constructs a new batch node.
  9342. *
  9343. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9344. */
  9345. constructor( batchMesh ) {
  9346. super( 'void' );
  9347. /**
  9348. * A reference to batched mesh.
  9349. *
  9350. * @type {BatchedMesh}
  9351. */
  9352. this.batchMesh = batchMesh;
  9353. /**
  9354. * The batching index node.
  9355. *
  9356. * @type {IndexNode?}
  9357. * @default null
  9358. */
  9359. this.batchingIdNode = null;
  9360. }
  9361. /**
  9362. * Setups the internal buffers and nodes and assigns the transformed vertex data
  9363. * to predefined node variables for accumulation. That follows the same patterns
  9364. * like with morph and skinning nodes.
  9365. *
  9366. * @param {NodeBuilder} builder - The current node builder.
  9367. */
  9368. setup( builder ) {
  9369. if ( this.batchingIdNode === null ) {
  9370. if ( builder.getDrawIndex() === null ) {
  9371. this.batchingIdNode = instanceIndex;
  9372. } else {
  9373. this.batchingIdNode = drawIndex;
  9374. }
  9375. }
  9376. const getIndirectIndex = Fn( ( [ id ] ) => {
  9377. const size = textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 );
  9378. const x = int( id ).modInt( int( size ) );
  9379. const y = int( id ).div( int( size ) );
  9380. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  9381. } ).setLayout( {
  9382. name: 'getIndirectIndex',
  9383. type: 'uint',
  9384. inputs: [
  9385. { name: 'id', type: 'int' }
  9386. ]
  9387. } );
  9388. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  9389. const matricesTexture = this.batchMesh._matricesTexture;
  9390. const size = textureSize( textureLoad( matricesTexture ), 0 );
  9391. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  9392. const x = j.modInt( size );
  9393. const y = j.div( int( size ) );
  9394. const batchingMatrix = mat4(
  9395. textureLoad( matricesTexture, ivec2( x, y ) ),
  9396. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  9397. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  9398. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  9399. );
  9400. const colorsTexture = this.batchMesh._colorsTexture;
  9401. if ( colorsTexture !== null ) {
  9402. const getBatchingColor = Fn( ( [ id ] ) => {
  9403. const size = textureSize( textureLoad( colorsTexture ), 0 ).x;
  9404. const j = id;
  9405. const x = j.modInt( size );
  9406. const y = j.div( size );
  9407. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  9408. } ).setLayout( {
  9409. name: 'getBatchingColor',
  9410. type: 'vec3',
  9411. inputs: [
  9412. { name: 'id', type: 'int' }
  9413. ]
  9414. } );
  9415. const color = getBatchingColor( indirectId );
  9416. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  9417. }
  9418. const bm = mat3( batchingMatrix );
  9419. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  9420. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  9421. const batchingNormal = bm.mul( transformedNormal ).xyz;
  9422. normalLocal.assign( batchingNormal );
  9423. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9424. tangentLocal.mulAssign( bm );
  9425. }
  9426. }
  9427. }
  9428. /**
  9429. * TSL function for creating a batch node.
  9430. *
  9431. * @function
  9432. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  9433. * @returns {BatchNode}
  9434. */
  9435. const batch = /*@__PURE__*/ nodeProxy( BatchNode );
  9436. /** @module SkinningNode **/
  9437. const _frameId = new WeakMap();
  9438. /**
  9439. * This node implements the vertex transformation shader logic which is required
  9440. * for skinning/skeletal animation.
  9441. *
  9442. * @augments Node
  9443. */
  9444. class SkinningNode extends Node {
  9445. static get type() {
  9446. return 'SkinningNode';
  9447. }
  9448. /**
  9449. * Constructs a new skinning node.
  9450. *
  9451. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9452. * @param {Boolean} [useReference=false] - Whether to use reference nodes for internal skinned mesh related data or not.
  9453. */
  9454. constructor( skinnedMesh, useReference = false ) {
  9455. super( 'void' );
  9456. /**
  9457. * The skinned mesh.
  9458. *
  9459. * @type {SkinnedMesh}
  9460. */
  9461. this.skinnedMesh = skinnedMesh;
  9462. /**
  9463. * Whether to use reference nodes for internal skinned mesh related data or not.
  9464. * TODO: Explain the purpose of the property.
  9465. *
  9466. * @type {Boolean}
  9467. */
  9468. this.useReference = useReference;
  9469. /**
  9470. * The update type overwritten since skinning nodes are updated per object.
  9471. *
  9472. * @type {String}
  9473. */
  9474. this.updateType = NodeUpdateType.OBJECT;
  9475. //
  9476. /**
  9477. * The skin index attribute.
  9478. *
  9479. * @type {AttributeNode}
  9480. */
  9481. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  9482. /**
  9483. * The skin weight attribute.
  9484. *
  9485. * @type {AttributeNode}
  9486. */
  9487. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  9488. let bindMatrixNode, bindMatrixInverseNode, boneMatricesNode;
  9489. if ( useReference ) {
  9490. bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  9491. bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  9492. boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9493. } else {
  9494. bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  9495. bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  9496. boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  9497. }
  9498. /**
  9499. * The bind matrix node.
  9500. *
  9501. * @type {Node<mat4>}
  9502. */
  9503. this.bindMatrixNode = bindMatrixNode;
  9504. /**
  9505. * The bind matrix inverse node.
  9506. *
  9507. * @type {Node<mat4>}
  9508. */
  9509. this.bindMatrixInverseNode = bindMatrixInverseNode;
  9510. /**
  9511. * The bind matrices as a uniform buffer node.
  9512. *
  9513. * @type {Node}
  9514. */
  9515. this.boneMatricesNode = boneMatricesNode;
  9516. /**
  9517. * The previous bind matrices as a uniform buffer node.
  9518. * Required for computing motion vectors.
  9519. *
  9520. * @type {Node?}
  9521. * @default null
  9522. */
  9523. this.previousBoneMatricesNode = null;
  9524. }
  9525. /**
  9526. * Transforms the given vertex position via skinning.
  9527. *
  9528. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9529. * @param {Node<vec3>} [position=positionLocal] - The vertex position in local space.
  9530. * @return {Node<vec3>} The transformed vertex position.
  9531. */
  9532. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = positionLocal ) {
  9533. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9534. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9535. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9536. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9537. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9538. // POSITION
  9539. const skinVertex = bindMatrixNode.mul( position );
  9540. const skinned = add(
  9541. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  9542. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  9543. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  9544. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  9545. );
  9546. return bindMatrixInverseNode.mul( skinned ).xyz;
  9547. }
  9548. /**
  9549. * Transforms the given vertex normal via skinning.
  9550. *
  9551. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  9552. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  9553. * @return {Node<vec3>} The transformed vertex normal.
  9554. */
  9555. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  9556. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  9557. const boneMatX = boneMatrices.element( skinIndexNode.x );
  9558. const boneMatY = boneMatrices.element( skinIndexNode.y );
  9559. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  9560. const boneMatW = boneMatrices.element( skinIndexNode.w );
  9561. // NORMAL
  9562. let skinMatrix = add(
  9563. skinWeightNode.x.mul( boneMatX ),
  9564. skinWeightNode.y.mul( boneMatY ),
  9565. skinWeightNode.z.mul( boneMatZ ),
  9566. skinWeightNode.w.mul( boneMatW )
  9567. );
  9568. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  9569. return skinMatrix.transformDirection( normal ).xyz;
  9570. }
  9571. /**
  9572. * Transforms the given vertex normal via skinning.
  9573. *
  9574. * @param {NodeBuilder} builder - The current node builder.
  9575. * @return {Node<vec3>} The skinned position from the previous frame.
  9576. */
  9577. getPreviousSkinnedPosition( builder ) {
  9578. const skinnedMesh = builder.object;
  9579. if ( this.previousBoneMatricesNode === null ) {
  9580. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  9581. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  9582. }
  9583. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  9584. }
  9585. /**
  9586. * Returns `true` if bone matrices from the previous frame are required.
  9587. *
  9588. * @param {NodeBuilder} builder - The current node builder.
  9589. * @return {Boolean} Whether bone matrices from the previous frame are required or not.
  9590. */
  9591. needsPreviousBoneMatrices( builder ) {
  9592. const mrt = builder.renderer.getMRT();
  9593. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  9594. }
  9595. /**
  9596. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  9597. *
  9598. * @param {NodeBuilder} builder - The current node builder.
  9599. */
  9600. setup( builder ) {
  9601. if ( this.needsPreviousBoneMatrices( builder ) ) {
  9602. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  9603. }
  9604. const skinPosition = this.getSkinnedPosition();
  9605. positionLocal.assign( skinPosition );
  9606. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  9607. const skinNormal = this.getSkinnedNormal();
  9608. normalLocal.assign( skinNormal );
  9609. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  9610. tangentLocal.assign( skinNormal );
  9611. }
  9612. }
  9613. }
  9614. /**
  9615. * Generates the code snippet of the skinning node.
  9616. *
  9617. * @param {NodeBuilder} builder - The current node builder.
  9618. * @param {String} output - The current output.
  9619. * @return {String} The generated code snippet.
  9620. */
  9621. generate( builder, output ) {
  9622. if ( output !== 'void' ) {
  9623. return positionLocal.build( builder, output );
  9624. }
  9625. }
  9626. /**
  9627. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  9628. *
  9629. * @param {NodeFrame} frame - The current node frame.
  9630. */
  9631. update( frame ) {
  9632. const object = this.useReference ? frame.object : this.skinnedMesh;
  9633. const skeleton = object.skeleton;
  9634. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  9635. _frameId.set( skeleton, frame.frameId );
  9636. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  9637. skeleton.update();
  9638. }
  9639. }
  9640. /**
  9641. * TSL function for creating a skinning node.
  9642. *
  9643. * @function
  9644. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9645. * @returns {SkinningNode}
  9646. */
  9647. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  9648. /**
  9649. * TSL function for creating a skinning node with reference usage.
  9650. *
  9651. * @function
  9652. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  9653. * @returns {SkinningNode}
  9654. */
  9655. const skinningReference = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh, true ) );
  9656. /** @module LoopNode **/
  9657. /**
  9658. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  9659. * ```js
  9660. * Loop( count, ( { i } ) => {
  9661. *
  9662. * } );
  9663. * ```
  9664. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  9665. * ```js
  9666. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  9667. *
  9668. * } );
  9669. *```
  9670. * Nested loops can be defined in a compacted form:
  9671. * ```js
  9672. * Loop( 10, 5, ( { i, j } ) => {
  9673. *
  9674. * } );
  9675. * ```
  9676. * Loops that should run backwards can be defined like so:
  9677. * ```js
  9678. * Loop( { start: 10 }, () => {} );
  9679. * ```
  9680. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  9681. * @augments Node
  9682. */
  9683. class LoopNode extends Node {
  9684. static get type() {
  9685. return 'LoopNode';
  9686. }
  9687. /**
  9688. * Constructs a new loop node.
  9689. *
  9690. * @param {Array<Any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  9691. */
  9692. constructor( params = [] ) {
  9693. super();
  9694. this.params = params;
  9695. }
  9696. /**
  9697. * Returns a loop variable name based on an index. The pattern is
  9698. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  9699. *
  9700. * @param {Number} index - The index.
  9701. * @return {String} The loop variable name.
  9702. */
  9703. getVarName( index ) {
  9704. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  9705. }
  9706. /**
  9707. * Returns properties about this node.
  9708. *
  9709. * @param {NodeBuilder} builder - The current node builder.
  9710. * @return {Object} The node properties.
  9711. */
  9712. getProperties( builder ) {
  9713. const properties = builder.getNodeProperties( this );
  9714. if ( properties.stackNode !== undefined ) return properties;
  9715. //
  9716. const inputs = {};
  9717. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9718. const param = this.params[ i ];
  9719. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  9720. const type = ( param.isNode !== true && param.type ) || 'int';
  9721. inputs[ name ] = expression( name, type );
  9722. }
  9723. const stack = builder.addStack(); // TODO: cache() it
  9724. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, stack, builder );
  9725. properties.stackNode = stack;
  9726. builder.removeStack();
  9727. return properties;
  9728. }
  9729. /**
  9730. * This method is overwritten since the node type is inferred based on the loop configuration.
  9731. *
  9732. * @param {NodeBuilder} builder - The current node builder.
  9733. * @return {String} The node type.
  9734. */
  9735. getNodeType( builder ) {
  9736. const { returnsNode } = this.getProperties( builder );
  9737. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  9738. }
  9739. setup( builder ) {
  9740. // setup properties
  9741. this.getProperties( builder );
  9742. }
  9743. generate( builder ) {
  9744. const properties = this.getProperties( builder );
  9745. const params = this.params;
  9746. const stackNode = properties.stackNode;
  9747. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  9748. const param = params[ i ];
  9749. let start = null, end = null, name = null, type = null, condition = null, update = null;
  9750. if ( param.isNode ) {
  9751. type = 'int';
  9752. name = this.getVarName( i );
  9753. start = '0';
  9754. end = param.build( builder, type );
  9755. condition = '<';
  9756. } else {
  9757. type = param.type || 'int';
  9758. name = param.name || this.getVarName( i );
  9759. start = param.start;
  9760. end = param.end;
  9761. condition = param.condition;
  9762. update = param.update;
  9763. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  9764. else if ( start && start.isNode ) start = start.build( builder, type );
  9765. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  9766. else if ( end && end.isNode ) end = end.build( builder, type );
  9767. if ( start !== undefined && end === undefined ) {
  9768. start = start + ' - 1';
  9769. end = '0';
  9770. condition = '>=';
  9771. } else if ( end !== undefined && start === undefined ) {
  9772. start = '0';
  9773. condition = '<';
  9774. }
  9775. if ( condition === undefined ) {
  9776. if ( Number( start ) > Number( end ) ) {
  9777. condition = '>=';
  9778. } else {
  9779. condition = '<';
  9780. }
  9781. }
  9782. }
  9783. const internalParam = { start, end, condition };
  9784. //
  9785. const startSnippet = internalParam.start;
  9786. const endSnippet = internalParam.end;
  9787. let declarationSnippet = '';
  9788. let conditionalSnippet = '';
  9789. let updateSnippet = '';
  9790. if ( ! update ) {
  9791. if ( type === 'int' || type === 'uint' ) {
  9792. if ( condition.includes( '<' ) ) update = '++';
  9793. else update = '--';
  9794. } else {
  9795. if ( condition.includes( '<' ) ) update = '+= 1.';
  9796. else update = '-= 1.';
  9797. }
  9798. }
  9799. declarationSnippet += builder.getVar( type, name ) + ' = ' + startSnippet;
  9800. conditionalSnippet += name + ' ' + condition + ' ' + endSnippet;
  9801. updateSnippet += name + ' ' + update;
  9802. const forSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  9803. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + forSnippet + ' {\n\n' ).addFlowTab();
  9804. }
  9805. const stackSnippet = stackNode.build( builder, 'void' );
  9806. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  9807. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  9808. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  9809. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  9810. }
  9811. builder.addFlowTab();
  9812. return returnsSnippet;
  9813. }
  9814. }
  9815. /**
  9816. * TSL function for creating a loop node.
  9817. *
  9818. * @function
  9819. * @param {...Any} params - A list of parameters.
  9820. * @returns {LoopNode}
  9821. */
  9822. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).append();
  9823. /**
  9824. * TSL function for creating a `Continue()` expression.
  9825. *
  9826. * @function
  9827. * @returns {ExpressionNode}
  9828. */
  9829. const Continue = () => expression( 'continue' ).append();
  9830. /**
  9831. * TSL function for creating a `Break()` expression.
  9832. *
  9833. * @function
  9834. * @returns {ExpressionNode}
  9835. */
  9836. const Break = () => expression( 'break' ).append();
  9837. // deprecated
  9838. /**
  9839. * @function
  9840. * @deprecated since r168. Use {@link Loop} instead.
  9841. *
  9842. * @param {...any} params
  9843. * @returns {LoopNode}
  9844. */
  9845. const loop = ( ...params ) => { // @deprecated, r168
  9846. console.warn( 'TSL.LoopNode: loop() has been renamed to Loop().' );
  9847. return Loop( ...params );
  9848. };
  9849. /** @module MorphNode **/
  9850. const _morphTextures = /*@__PURE__*/ new WeakMap();
  9851. const _morphVec4 = /*@__PURE__*/ new Vector4();
  9852. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  9853. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  9854. const y = texelIndex.div( width );
  9855. const x = texelIndex.sub( y.mul( width ) );
  9856. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth );
  9857. return bufferAttrib.mul( influence );
  9858. } );
  9859. function getEntry( geometry ) {
  9860. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9861. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  9862. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  9863. // instead of using attributes, the WebGL 2 code path encodes morph targets
  9864. // into an array of data textures. Each layer represents a single morph target.
  9865. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9866. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9867. let entry = _morphTextures.get( geometry );
  9868. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  9869. if ( entry !== undefined ) entry.texture.dispose();
  9870. const morphTargets = geometry.morphAttributes.position || [];
  9871. const morphNormals = geometry.morphAttributes.normal || [];
  9872. const morphColors = geometry.morphAttributes.color || [];
  9873. let vertexDataCount = 0;
  9874. if ( hasMorphPosition === true ) vertexDataCount = 1;
  9875. if ( hasMorphNormals === true ) vertexDataCount = 2;
  9876. if ( hasMorphColors === true ) vertexDataCount = 3;
  9877. let width = geometry.attributes.position.count * vertexDataCount;
  9878. let height = 1;
  9879. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  9880. if ( width > maxTextureSize ) {
  9881. height = Math.ceil( width / maxTextureSize );
  9882. width = maxTextureSize;
  9883. }
  9884. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  9885. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  9886. bufferTexture.type = FloatType;
  9887. bufferTexture.needsUpdate = true;
  9888. // fill buffer
  9889. const vertexDataStride = vertexDataCount * 4;
  9890. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  9891. const morphTarget = morphTargets[ i ];
  9892. const morphNormal = morphNormals[ i ];
  9893. const morphColor = morphColors[ i ];
  9894. const offset = width * height * 4 * i;
  9895. for ( let j = 0; j < morphTarget.count; j ++ ) {
  9896. const stride = j * vertexDataStride;
  9897. if ( hasMorphPosition === true ) {
  9898. _morphVec4.fromBufferAttribute( morphTarget, j );
  9899. buffer[ offset + stride + 0 ] = _morphVec4.x;
  9900. buffer[ offset + stride + 1 ] = _morphVec4.y;
  9901. buffer[ offset + stride + 2 ] = _morphVec4.z;
  9902. buffer[ offset + stride + 3 ] = 0;
  9903. }
  9904. if ( hasMorphNormals === true ) {
  9905. _morphVec4.fromBufferAttribute( morphNormal, j );
  9906. buffer[ offset + stride + 4 ] = _morphVec4.x;
  9907. buffer[ offset + stride + 5 ] = _morphVec4.y;
  9908. buffer[ offset + stride + 6 ] = _morphVec4.z;
  9909. buffer[ offset + stride + 7 ] = 0;
  9910. }
  9911. if ( hasMorphColors === true ) {
  9912. _morphVec4.fromBufferAttribute( morphColor, j );
  9913. buffer[ offset + stride + 8 ] = _morphVec4.x;
  9914. buffer[ offset + stride + 9 ] = _morphVec4.y;
  9915. buffer[ offset + stride + 10 ] = _morphVec4.z;
  9916. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  9917. }
  9918. }
  9919. }
  9920. entry = {
  9921. count: morphTargetsCount,
  9922. texture: bufferTexture,
  9923. stride: vertexDataCount,
  9924. size: new Vector2( width, height )
  9925. };
  9926. _morphTextures.set( geometry, entry );
  9927. function disposeTexture() {
  9928. bufferTexture.dispose();
  9929. _morphTextures.delete( geometry );
  9930. geometry.removeEventListener( 'dispose', disposeTexture );
  9931. }
  9932. geometry.addEventListener( 'dispose', disposeTexture );
  9933. }
  9934. return entry;
  9935. }
  9936. /**
  9937. * This node implements the vertex transformation shader logic which is required
  9938. * for morph target animation.
  9939. *
  9940. * @augments Node
  9941. */
  9942. class MorphNode extends Node {
  9943. static get type() {
  9944. return 'MorphNode';
  9945. }
  9946. /**
  9947. * Constructs a new morph node.
  9948. *
  9949. * @param {Mesh} mesh - The mesh holding the morph targets.
  9950. */
  9951. constructor( mesh ) {
  9952. super( 'void' );
  9953. /**
  9954. * The mesh holding the morph targets.
  9955. *
  9956. * @type {Mesh}
  9957. */
  9958. this.mesh = mesh;
  9959. /**
  9960. * A uniform node which represents the morph base influence value.
  9961. *
  9962. * @type {UniformNode<float>}
  9963. */
  9964. this.morphBaseInfluence = uniform( 1 );
  9965. /**
  9966. * The update type overwritten since morph nodes are updated per object.
  9967. *
  9968. * @type {String}
  9969. */
  9970. this.updateType = NodeUpdateType.OBJECT;
  9971. }
  9972. /**
  9973. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  9974. *
  9975. * @param {NodeBuilder} builder - The current node builder.
  9976. */
  9977. setup( builder ) {
  9978. const { geometry } = builder;
  9979. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  9980. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  9981. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  9982. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  9983. // nodes
  9984. const { texture: bufferMap, stride, size } = getEntry( geometry );
  9985. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  9986. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  9987. const width = int( size.width );
  9988. Loop( morphTargetsCount, ( { i } ) => {
  9989. const influence = float( 0 ).toVar();
  9990. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  9991. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  9992. } else {
  9993. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  9994. }
  9995. if ( hasMorphPosition === true ) {
  9996. positionLocal.addAssign( getMorph( {
  9997. bufferMap,
  9998. influence,
  9999. stride,
  10000. width,
  10001. depth: i,
  10002. offset: int( 0 )
  10003. } ) );
  10004. }
  10005. if ( hasMorphNormals === true ) {
  10006. normalLocal.addAssign( getMorph( {
  10007. bufferMap,
  10008. influence,
  10009. stride,
  10010. width,
  10011. depth: i,
  10012. offset: int( 1 )
  10013. } ) );
  10014. }
  10015. } );
  10016. }
  10017. /**
  10018. * Updates the state of the morphed mesh by updating the base influence.
  10019. *
  10020. * @param {NodeFrame} frame - The current node frame.
  10021. */
  10022. update( /*frame*/ ) {
  10023. const morphBaseInfluence = this.morphBaseInfluence;
  10024. if ( this.mesh.geometry.morphTargetsRelative ) {
  10025. morphBaseInfluence.value = 1;
  10026. } else {
  10027. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  10028. }
  10029. }
  10030. }
  10031. /**
  10032. * TSL function for creating a morph node.
  10033. *
  10034. * @function
  10035. * @param {Mesh} mesh - The mesh holding the morph targets.
  10036. * @returns {MorphNode}
  10037. */
  10038. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode );
  10039. /**
  10040. * Base class for lighting nodes.
  10041. *
  10042. * @augments Node
  10043. */
  10044. class LightingNode extends Node {
  10045. static get type() {
  10046. return 'LightingNode';
  10047. }
  10048. /**
  10049. * Constructs a new lighting node.
  10050. */
  10051. constructor() {
  10052. super( 'vec3' );
  10053. /**
  10054. * This flag can be used for type testing.
  10055. *
  10056. * @type {Boolean}
  10057. * @readonly
  10058. * @default true
  10059. */
  10060. this.isLightingNode = true;
  10061. }
  10062. }
  10063. /**
  10064. * A generic class that can be used by nodes which contribute
  10065. * ambient occlusion to the scene. E.g. an ambient occlusion map
  10066. * node can be used as input for this module. Used in {@link NodeMaterial}.
  10067. *
  10068. * @augments LightingNode
  10069. */
  10070. class AONode extends LightingNode {
  10071. static get type() {
  10072. return 'AONode';
  10073. }
  10074. /**
  10075. * Constructs a new AO node.
  10076. *
  10077. * @param {Node<float>?} [aoNode=null] - The ambient occlusion node.
  10078. */
  10079. constructor( aoNode = null ) {
  10080. super();
  10081. /**
  10082. * The ambient occlusion node.
  10083. *
  10084. * @type {Node<float>?}
  10085. * @default null
  10086. */
  10087. this.aoNode = aoNode;
  10088. }
  10089. setup( builder ) {
  10090. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  10091. }
  10092. }
  10093. /**
  10094. * `LightingContextNode` represents an extension of the {@link module:ContextNode~ContextNode} module
  10095. * by adding lighting specific context data. It represents the runtime context of
  10096. * {@link LightsNode}.
  10097. *
  10098. * @augments ContextNode
  10099. */
  10100. class LightingContextNode extends ContextNode {
  10101. static get type() {
  10102. return 'LightingContextNode';
  10103. }
  10104. /**
  10105. * Constructs a new lighting context node.
  10106. *
  10107. * @param {LightsNode} node - The lights node.
  10108. * @param {LightingModel?} [lightingModel=null] - The current lighting model.
  10109. * @param {Node<vec3>?} [backdropNode=null] - A backdrop node.
  10110. * @param {Node<float>?} [backdropAlphaNode=null] - A backdrop alpha node.
  10111. */
  10112. constructor( node, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  10113. super( node );
  10114. /**
  10115. * The current lighting model.
  10116. *
  10117. * @type {LightingModel?}
  10118. * @default null
  10119. */
  10120. this.lightingModel = lightingModel;
  10121. /**
  10122. * A backdrop node.
  10123. *
  10124. * @type {Node<vec3>?}
  10125. * @default null
  10126. */
  10127. this.backdropNode = backdropNode;
  10128. /**
  10129. * A backdrop alpha node.
  10130. *
  10131. * @type {Node<float>?}
  10132. * @default null
  10133. */
  10134. this.backdropAlphaNode = backdropAlphaNode;
  10135. this._value = null;
  10136. }
  10137. /**
  10138. * Returns a lighting context object.
  10139. *
  10140. * @return {{
  10141. * radiance: Node<vec3>,
  10142. * irradiance: Node<vec3>,
  10143. * iblIrradiance: Node<vec3>,
  10144. * ambientOcclusion: Node<float>,
  10145. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  10146. * backdrop: Node<vec3>,
  10147. * backdropAlpha: Node<float>
  10148. * }} The lighting context object.
  10149. */
  10150. getContext() {
  10151. const { backdropNode, backdropAlphaNode } = this;
  10152. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  10153. directSpecular = vec3().toVar( 'directSpecular' ),
  10154. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  10155. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  10156. const reflectedLight = {
  10157. directDiffuse,
  10158. directSpecular,
  10159. indirectDiffuse,
  10160. indirectSpecular
  10161. };
  10162. const context = {
  10163. radiance: vec3().toVar( 'radiance' ),
  10164. irradiance: vec3().toVar( 'irradiance' ),
  10165. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  10166. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  10167. reflectedLight,
  10168. backdrop: backdropNode,
  10169. backdropAlpha: backdropAlphaNode
  10170. };
  10171. return context;
  10172. }
  10173. setup( builder ) {
  10174. this.value = this._value || ( this._value = this.getContext() );
  10175. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  10176. return super.setup( builder );
  10177. }
  10178. }
  10179. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  10180. /**
  10181. * A generic class that can be used by nodes which contribute
  10182. * irradiance to the scene. E.g. a light map node can be used
  10183. * as input for this module. Used in {@link NodeMaterial}.
  10184. *
  10185. * @augments LightingNode
  10186. */
  10187. class IrradianceNode extends LightingNode {
  10188. static get type() {
  10189. return 'IrradianceNode';
  10190. }
  10191. /**
  10192. * Constructs a new irradiance node.
  10193. *
  10194. * @param {Node<vec3>} node - A node contributing irradiance.
  10195. */
  10196. constructor( node ) {
  10197. super();
  10198. /**
  10199. * A node contributing irradiance.
  10200. *
  10201. * @type {Node<vec3>}
  10202. */
  10203. this.node = node;
  10204. }
  10205. setup( builder ) {
  10206. builder.context.irradiance.addAssign( this.node );
  10207. }
  10208. }
  10209. /** @module ScreenNode **/
  10210. let screenSizeVec, viewportVec;
  10211. /**
  10212. * This node provides a collection of screen related metrics.
  10213. * Depending on {@link module:ScreenNode~ScreenNode#scope}, the nodes can represent
  10214. * resolution or viewport data as well as fragment or uv coordinates.
  10215. *
  10216. * @augments Node
  10217. */
  10218. class ScreenNode extends Node {
  10219. static get type() {
  10220. return 'ScreenNode';
  10221. }
  10222. /**
  10223. * Constructs a new screen node.
  10224. *
  10225. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  10226. */
  10227. constructor( scope ) {
  10228. super();
  10229. /**
  10230. * The node represents different metric depending on which scope is selected.
  10231. *
  10232. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  10233. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  10234. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  10235. * - `ScreenNode.UV`: Normalized coordinates.
  10236. *
  10237. * @type {('coordinate'|'viewport'|'size'|'uv')}
  10238. */
  10239. this.scope = scope;
  10240. /**
  10241. * This flag can be used for type testing.
  10242. *
  10243. * @type {Boolean}
  10244. * @readonly
  10245. * @default true
  10246. */
  10247. this.isViewportNode = true;
  10248. }
  10249. /**
  10250. * This method is overwritten since the node type depends on the selected scope.
  10251. *
  10252. * @return {('vec2'|'vec4')} The node type.
  10253. */
  10254. getNodeType() {
  10255. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  10256. else return 'vec2';
  10257. }
  10258. /**
  10259. * This method is overwritten since the node's update type depends on the selected scope.
  10260. *
  10261. * @return {NodeUpdateType} The update type.
  10262. */
  10263. getUpdateType() {
  10264. let updateType = NodeUpdateType.NONE;
  10265. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  10266. updateType = NodeUpdateType.RENDER;
  10267. }
  10268. this.updateType = updateType;
  10269. return updateType;
  10270. }
  10271. /**
  10272. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  10273. * from the current renderer.
  10274. *
  10275. * @param {NodeFrame} frame - A reference to the current node frame.
  10276. */
  10277. update( { renderer } ) {
  10278. const renderTarget = renderer.getRenderTarget();
  10279. if ( this.scope === ScreenNode.VIEWPORT ) {
  10280. if ( renderTarget !== null ) {
  10281. viewportVec.copy( renderTarget.viewport );
  10282. } else {
  10283. renderer.getViewport( viewportVec );
  10284. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  10285. }
  10286. } else {
  10287. if ( renderTarget !== null ) {
  10288. screenSizeVec.width = renderTarget.width;
  10289. screenSizeVec.height = renderTarget.height;
  10290. } else {
  10291. renderer.getDrawingBufferSize( screenSizeVec );
  10292. }
  10293. }
  10294. }
  10295. setup( /*builder*/ ) {
  10296. const scope = this.scope;
  10297. let output = null;
  10298. if ( scope === ScreenNode.SIZE ) {
  10299. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  10300. } else if ( scope === ScreenNode.VIEWPORT ) {
  10301. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  10302. } else {
  10303. output = vec2( screenCoordinate.div( screenSize ) );
  10304. }
  10305. return output;
  10306. }
  10307. generate( builder ) {
  10308. if ( this.scope === ScreenNode.COORDINATE ) {
  10309. let coord = builder.getFragCoord();
  10310. if ( builder.isFlipY() ) {
  10311. // follow webgpu standards
  10312. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  10313. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  10314. }
  10315. return coord;
  10316. }
  10317. return super.generate( builder );
  10318. }
  10319. }
  10320. ScreenNode.COORDINATE = 'coordinate';
  10321. ScreenNode.VIEWPORT = 'viewport';
  10322. ScreenNode.SIZE = 'size';
  10323. ScreenNode.UV = 'uv';
  10324. // Screen
  10325. /**
  10326. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  10327. *
  10328. * @type {ScreenNode<vec2>}
  10329. */
  10330. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  10331. /**
  10332. * TSL object that represents the screen resolution in physical pixel units.
  10333. *
  10334. * @type {ScreenNode<vec2>}
  10335. */
  10336. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  10337. /**
  10338. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  10339. *
  10340. * @type {ScreenNode<vec2>}
  10341. */
  10342. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  10343. // Viewport
  10344. /**
  10345. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  10346. *
  10347. * @type {ScreenNode<vec4>}
  10348. */
  10349. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  10350. /**
  10351. * TSL object that represents the viewport resolution in physical pixel units.
  10352. *
  10353. * @type {ScreenNode<vec2>}
  10354. */
  10355. const viewportSize = viewport.zw;
  10356. /**
  10357. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  10358. *
  10359. * @type {ScreenNode<vec2>}
  10360. */
  10361. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  10362. /**
  10363. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  10364. *
  10365. * @type {ScreenNode<vec2>}
  10366. */
  10367. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  10368. // Deprecated
  10369. /**
  10370. * @deprecated since r169. Use {@link screenSize} instead.
  10371. */
  10372. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  10373. console.warn( 'TSL.ViewportNode: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  10374. return screenSize;
  10375. }, 'vec2' ).once() )();
  10376. /**
  10377. * @deprecated since r168. Use {@link screenUV} instead.
  10378. */
  10379. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10380. console.warn( 'TSL.ViewportNode: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  10381. return screenUV;
  10382. }, 'vec2' ).once() )();
  10383. /**
  10384. * @deprecated since r168. Use `screenUV.flipY()` instead.
  10385. */
  10386. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  10387. console.warn( 'TSL.ViewportNode: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  10388. return screenUV.flipY();
  10389. }, 'vec2' ).once() )();
  10390. /** @module ViewportTextureNode **/
  10391. const _size$4 = /*@__PURE__*/ new Vector2();
  10392. /**
  10393. * A special type of texture node which represents the data of the current viewport
  10394. * as a texture. The module extracts data from the current bound framebuffer with
  10395. * a copy operation so no extra render pass is required to produce the texture data
  10396. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  10397. * variety of effects like refractive or transmissive materials.
  10398. *
  10399. * @augments module:TextureNode~TextureNode
  10400. */
  10401. class ViewportTextureNode extends TextureNode {
  10402. static get type() {
  10403. return 'ViewportTextureNode';
  10404. }
  10405. /**
  10406. * Constructs a new viewport texture node.
  10407. *
  10408. * @param {Node} [uvNode=screenUV] - The uv node.
  10409. * @param {Node?} [levelNode=null] - The level node.
  10410. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10411. */
  10412. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  10413. if ( framebufferTexture === null ) {
  10414. framebufferTexture = new FramebufferTexture();
  10415. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  10416. }
  10417. super( framebufferTexture, uvNode, levelNode );
  10418. /**
  10419. * Whether to generate mipmaps or not.
  10420. *
  10421. * @type {Boolean}
  10422. * @default false
  10423. */
  10424. this.generateMipmaps = false;
  10425. /**
  10426. * This flag can be used for type testing.
  10427. *
  10428. * @type {Boolean}
  10429. * @readonly
  10430. * @default true
  10431. */
  10432. this.isOutputTextureNode = true;
  10433. /**
  10434. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  10435. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  10436. *
  10437. * @type {String}
  10438. * @default 'frame'
  10439. */
  10440. this.updateBeforeType = NodeUpdateType.FRAME;
  10441. }
  10442. updateBefore( frame ) {
  10443. const renderer = frame.renderer;
  10444. renderer.getDrawingBufferSize( _size$4 );
  10445. //
  10446. const framebufferTexture = this.value;
  10447. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  10448. framebufferTexture.image.width = _size$4.width;
  10449. framebufferTexture.image.height = _size$4.height;
  10450. framebufferTexture.needsUpdate = true;
  10451. }
  10452. //
  10453. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  10454. framebufferTexture.generateMipmaps = this.generateMipmaps;
  10455. renderer.copyFramebufferToTexture( framebufferTexture );
  10456. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  10457. }
  10458. clone() {
  10459. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  10460. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  10461. return viewportTextureNode;
  10462. }
  10463. }
  10464. /**
  10465. * TSL function for creating a viewport texture node.
  10466. *
  10467. * @function
  10468. * @param {Node} [uvNode=screenUV] - The uv node.
  10469. * @param {Node?} [levelNode=null] - The level node.
  10470. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10471. * @returns {ViewportTextureNode}
  10472. */
  10473. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode );
  10474. /**
  10475. * TSL function for creating a viewport texture node with enabled mipmap generation.
  10476. *
  10477. * @function
  10478. * @param {Node} [uvNode=screenUV] - The uv node.
  10479. * @param {Node?} [levelNode=null] - The level node.
  10480. * @param {Texture?} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  10481. * @returns {ViewportTextureNode}
  10482. */
  10483. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } );
  10484. /** @module ViewportDepthTextureNode **/
  10485. let sharedDepthbuffer = null;
  10486. /**
  10487. * Represents the depth of the current viewport as a texture. This module
  10488. * can be used in combination with viewport texture to achieve effects
  10489. * that require depth evaluation.
  10490. *
  10491. * @augments module:ViewportTextureNode~ViewportTextureNode
  10492. */
  10493. class ViewportDepthTextureNode extends ViewportTextureNode {
  10494. static get type() {
  10495. return 'ViewportDepthTextureNode';
  10496. }
  10497. /**
  10498. * Constructs a new viewport depth texture node.
  10499. *
  10500. * @param {Node} [uvNode=screenUV] - The uv node.
  10501. * @param {Node?} [levelNode=null] - The level node.
  10502. */
  10503. constructor( uvNode = screenUV, levelNode = null ) {
  10504. if ( sharedDepthbuffer === null ) {
  10505. sharedDepthbuffer = new DepthTexture();
  10506. }
  10507. super( uvNode, levelNode, sharedDepthbuffer );
  10508. }
  10509. }
  10510. /**
  10511. * TSL function for a viewport depth texture node.
  10512. *
  10513. * @function
  10514. * @param {Node} [uvNode=screenUV] - The uv node.
  10515. * @param {Node?} [levelNode=null] - The level node.
  10516. * @returns {ViewportDepthTextureNode}
  10517. */
  10518. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode );
  10519. /** @module ViewportDepthNode **/
  10520. /**
  10521. * This node offers a collection of features in context of the depth logic in the fragment shader.
  10522. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  10523. * fragment or for depth evaluation purposes.
  10524. *
  10525. * @augments Node
  10526. */
  10527. class ViewportDepthNode extends Node {
  10528. static get type() {
  10529. return 'ViewportDepthNode';
  10530. }
  10531. /**
  10532. * Constructs a new viewport depth node.
  10533. *
  10534. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  10535. * @param {Node?} [valueNode=null] - The value node.
  10536. */
  10537. constructor( scope, valueNode = null ) {
  10538. super( 'float' );
  10539. /**
  10540. * The node behaves differently depending on which scope is selected.
  10541. *
  10542. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  10543. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  10544. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  10545. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  10546. *
  10547. * @type {('depth'|'depthBase'|'linearDepth')}
  10548. */
  10549. this.scope = scope;
  10550. /**
  10551. * Can be used to define a custom depth value.
  10552. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  10553. *
  10554. * @type {Node?}
  10555. * @default null
  10556. */
  10557. this.valueNode = valueNode;
  10558. /**
  10559. * This flag can be used for type testing.
  10560. *
  10561. * @type {Boolean}
  10562. * @readonly
  10563. * @default true
  10564. */
  10565. this.isViewportDepthNode = true;
  10566. }
  10567. generate( builder ) {
  10568. const { scope } = this;
  10569. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10570. return builder.getFragDepth();
  10571. }
  10572. return super.generate( builder );
  10573. }
  10574. setup( { camera } ) {
  10575. const { scope } = this;
  10576. const value = this.valueNode;
  10577. let node = null;
  10578. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  10579. if ( value !== null ) {
  10580. node = depthBase().assign( value );
  10581. }
  10582. } else if ( scope === ViewportDepthNode.DEPTH ) {
  10583. if ( camera.isPerspectiveCamera ) {
  10584. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  10585. } else {
  10586. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10587. }
  10588. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  10589. if ( value !== null ) {
  10590. if ( camera.isPerspectiveCamera ) {
  10591. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  10592. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  10593. } else {
  10594. node = value;
  10595. }
  10596. } else {
  10597. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  10598. }
  10599. }
  10600. return node;
  10601. }
  10602. }
  10603. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  10604. ViewportDepthNode.DEPTH = 'depth';
  10605. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  10606. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  10607. /**
  10608. * TSL function for converting a viewZ value to an orthographic depth value.
  10609. *
  10610. * @function
  10611. * @param {Node<float>} viewZ - The viewZ node.
  10612. * @param {Node<float>} near - The camera's near value.
  10613. * @param {Node<float>} far - The camera's far value.
  10614. * @returns {Node<float>}
  10615. */
  10616. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  10617. /**
  10618. * TSL function for converting an orthographic depth value to a viewZ value.
  10619. *
  10620. * @function
  10621. * @param {Node<float>} depth - The orthographic depth.
  10622. * @param {Node<float>} near - The camera's near value.
  10623. * @param {Node<float>} far - The camera's far value.
  10624. * @returns {Node<float>}
  10625. */
  10626. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  10627. /**
  10628. * TSL function for converting a viewZ value to a perspective depth value.
  10629. *
  10630. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  10631. *
  10632. * @function
  10633. * @param {Node<float>} viewZ - The viewZ node.
  10634. * @param {Node<float>} near - The camera's near value.
  10635. * @param {Node<float>} far - The camera's far value.
  10636. * @returns {Node<float>}
  10637. */
  10638. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  10639. /**
  10640. * TSL function for converting a perspective depth value to a viewZ value.
  10641. *
  10642. * @function
  10643. * @param {Node<float>} depth - The perspective depth.
  10644. * @param {Node<float>} near - The camera's near value.
  10645. * @param {Node<float>} far - The camera's far value.
  10646. * @returns {Node<float>}
  10647. */
  10648. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  10649. /**
  10650. * TSL function for converting a viewZ value to a logarithmic depth value.
  10651. *
  10652. * @function
  10653. * @param {Node<float>} viewZ - The viewZ node.
  10654. * @param {Node<float>} near - The camera's near value.
  10655. * @param {Node<float>} far - The camera's far value.
  10656. * @returns {Node<float>}
  10657. */
  10658. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  10659. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  10660. // The final logarithmic depth formula used here is adapted from one described in an
  10661. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  10662. // which was an improvement upon an earlier formula one described in an
  10663. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  10664. // Ulrich's formula is the following:
  10665. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  10666. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  10667. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  10668. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  10669. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  10670. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  10671. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  10672. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  10673. // be used, and ultimately Ulrich's "near plane" version was chosen.
  10674. // Outerra eventually made another improvement to their original "C-constant" variant,
  10675. // but it still does not incorporate the camera near plane (for this version,
  10676. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  10677. // Here we make 4 changes to Ulrich's formula:
  10678. // 1. Clamp the camera near plane so we don't divide by 0.
  10679. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  10680. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  10681. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  10682. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  10683. // so we do the same here, hence the 'viewZ.negate()' call.
  10684. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  10685. near = near.max( 1e-6 ).toVar();
  10686. const numerator = log2( viewZ.negate().div( near ) );
  10687. const denominator = log2( far.div( near ) );
  10688. return numerator.div( denominator );
  10689. };
  10690. /**
  10691. * TSL function for converting a logarithmic depth value to a viewZ value.
  10692. *
  10693. * @function
  10694. * @param {Node<float>} depth - The logarithmic depth.
  10695. * @param {Node<float>} near - The camera's near value.
  10696. * @param {Node<float>} far - The camera's far value.
  10697. * @returns {Node<float>}
  10698. */
  10699. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  10700. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  10701. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  10702. // a negative viewZ).
  10703. const exponent = depth.mul( log( far.div( near ) ) );
  10704. return float( Math.E ).pow( exponent ).mul( near ).negate();
  10705. };
  10706. /**
  10707. * TSL function for defining a value for the current fragment's depth.
  10708. *
  10709. * @function
  10710. * @param {Node<float>} value - The depth value to set.
  10711. * @returns {ViewportDepthNode<float>}
  10712. */
  10713. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  10714. /**
  10715. * TSL object that represents the depth value for the current fragment.
  10716. *
  10717. * @type {ViewportDepthNode}
  10718. */
  10719. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  10720. /**
  10721. * TSL function for converting a perspective depth value to linear depth.
  10722. *
  10723. * @function
  10724. * @param {Node<float>} value - The perspective depth.
  10725. * @returns {ViewportDepthNode<float>}
  10726. */
  10727. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH );
  10728. /**
  10729. * TSL object that represents the linear (orthographic) depth value of the current fragment
  10730. *
  10731. * @type {ViewportDepthNode}
  10732. */
  10733. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  10734. depth.assign = ( value ) => depthBase( value );
  10735. /** @module BuiltinNode **/
  10736. /**
  10737. * The node allows to set values for built-in shader variables. That is
  10738. * required for features like hardware-accelerated vertex clipping.
  10739. *
  10740. * @augments Node
  10741. */
  10742. class BuiltinNode extends Node {
  10743. /**
  10744. * Constructs a new builtin node.
  10745. *
  10746. * @param {String} name - The name of the built-in shader variable.
  10747. */
  10748. constructor( name ) {
  10749. super( 'float' );
  10750. /**
  10751. * The name of the built-in shader variable.
  10752. *
  10753. * @type {String}
  10754. */
  10755. this.name = name;
  10756. /**
  10757. * This flag can be used for type testing.
  10758. *
  10759. * @type {Boolean}
  10760. * @readonly
  10761. * @default true
  10762. */
  10763. this.isBuiltinNode = true;
  10764. }
  10765. /**
  10766. * Generates the code snippet of the builtin node.
  10767. *
  10768. * @param {NodeBuilder} builder - The current node builder.
  10769. * @return {String} The generated code snippet.
  10770. */
  10771. generate( /* builder */ ) {
  10772. return this.name;
  10773. }
  10774. }
  10775. /**
  10776. * TSL function for creating a builtin node.
  10777. *
  10778. * @function
  10779. * @param {String} name - The name of the built-in shader variable.
  10780. * @returns {BuiltinNode}
  10781. */
  10782. const builtin = nodeProxy( BuiltinNode );
  10783. /** @module ClippingNode **/
  10784. /**
  10785. * ```
  10786. * This node is used in {@link NodeMaterial} to setup the clipping
  10787. * which can happen hardware-accelerated (if supported) and optionally
  10788. * use alpha-to-coverage for anti-aliasing clipped edges.
  10789. * ```
  10790. * @augments Node
  10791. */
  10792. class ClippingNode extends Node {
  10793. static get type() {
  10794. return 'ClippingNode';
  10795. }
  10796. /**
  10797. * Constructs a new clipping node.
  10798. *
  10799. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  10800. * the selected scope influences the behavior of the node and what type of code is generated.
  10801. */
  10802. constructor( scope = ClippingNode.DEFAULT ) {
  10803. super();
  10804. /**
  10805. * The node's scope. Similar to other nodes, the selected scope influences
  10806. * the behavior of the node and what type of code is generated.
  10807. *
  10808. * @type {('default'|'hardware'|'alphaToCoverage')}
  10809. */
  10810. this.scope = scope;
  10811. }
  10812. /**
  10813. * Setups the node depending on the selected scope.
  10814. *
  10815. * @param {NodeBuilder} builder - The current node builder.
  10816. * @return {Node} The result node.
  10817. */
  10818. setup( builder ) {
  10819. super.setup( builder );
  10820. const clippingContext = builder.clippingContext;
  10821. const { intersectionPlanes, unionPlanes } = clippingContext;
  10822. this.hardwareClipping = builder.material.hardwareClipping;
  10823. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  10824. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  10825. } else if ( this.scope === ClippingNode.HARDWARE ) {
  10826. return this.setupHardwareClipping( unionPlanes, builder );
  10827. } else {
  10828. return this.setupDefault( intersectionPlanes, unionPlanes );
  10829. }
  10830. }
  10831. /**
  10832. * Setups alpha to coverage.
  10833. *
  10834. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10835. * @param {Array<Vector4>} unionPlanes - The union planes.
  10836. * @return {Node} The result node.
  10837. */
  10838. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  10839. return Fn( () => {
  10840. const distanceToPlane = float().toVar( 'distanceToPlane' );
  10841. const distanceGradient = float().toVar( 'distanceToGradient' );
  10842. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  10843. const numUnionPlanes = unionPlanes.length;
  10844. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10845. const clippingPlanes = uniformArray( unionPlanes );
  10846. Loop( numUnionPlanes, ( { i } ) => {
  10847. const plane = clippingPlanes.element( i );
  10848. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10849. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10850. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  10851. } );
  10852. }
  10853. const numIntersectionPlanes = intersectionPlanes.length;
  10854. if ( numIntersectionPlanes > 0 ) {
  10855. const clippingPlanes = uniformArray( intersectionPlanes );
  10856. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  10857. Loop( numIntersectionPlanes, ( { i } ) => {
  10858. const plane = clippingPlanes.element( i );
  10859. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  10860. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  10861. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  10862. } );
  10863. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  10864. }
  10865. diffuseColor.a.mulAssign( clipOpacity );
  10866. diffuseColor.a.equal( 0.0 ).discard();
  10867. } )();
  10868. }
  10869. /**
  10870. * Setups the default clipping.
  10871. *
  10872. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  10873. * @param {Array<Vector4>} unionPlanes - The union planes.
  10874. * @return {Node} The result node.
  10875. */
  10876. setupDefault( intersectionPlanes, unionPlanes ) {
  10877. return Fn( () => {
  10878. const numUnionPlanes = unionPlanes.length;
  10879. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  10880. const clippingPlanes = uniformArray( unionPlanes );
  10881. Loop( numUnionPlanes, ( { i } ) => {
  10882. const plane = clippingPlanes.element( i );
  10883. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  10884. } );
  10885. }
  10886. const numIntersectionPlanes = intersectionPlanes.length;
  10887. if ( numIntersectionPlanes > 0 ) {
  10888. const clippingPlanes = uniformArray( intersectionPlanes );
  10889. const clipped = bool( true ).toVar( 'clipped' );
  10890. Loop( numIntersectionPlanes, ( { i } ) => {
  10891. const plane = clippingPlanes.element( i );
  10892. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  10893. } );
  10894. clipped.discard();
  10895. }
  10896. } )();
  10897. }
  10898. /**
  10899. * Setups hardware clipping.
  10900. *
  10901. * @param {Array<Vector4>} unionPlanes - The union planes.
  10902. * @param {NodeBuilder} builder - The current node builder.
  10903. * @return {Node} The result node.
  10904. */
  10905. setupHardwareClipping( unionPlanes, builder ) {
  10906. const numUnionPlanes = unionPlanes.length;
  10907. builder.enableHardwareClipping( numUnionPlanes );
  10908. return Fn( () => {
  10909. const clippingPlanes = uniformArray( unionPlanes );
  10910. const hw_clip_distances = builtin( builder.getClipDistance() );
  10911. Loop( numUnionPlanes, ( { i } ) => {
  10912. const plane = clippingPlanes.element( i );
  10913. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  10914. hw_clip_distances.element( i ).assign( distance );
  10915. } );
  10916. } )();
  10917. }
  10918. }
  10919. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  10920. ClippingNode.DEFAULT = 'default';
  10921. ClippingNode.HARDWARE = 'hardware';
  10922. /**
  10923. * TSL function for setting up the default clipping logic.
  10924. *
  10925. * @function
  10926. * @returns {ClippingNode}
  10927. */
  10928. const clipping = () => nodeObject( new ClippingNode() );
  10929. /**
  10930. * TSL function for setting up alpha to coverage.
  10931. *
  10932. * @function
  10933. * @returns {ClippingNode}
  10934. */
  10935. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  10936. /**
  10937. * TSL function for setting up hardware-based clipping.
  10938. *
  10939. * @function
  10940. * @returns {ClippingNode}
  10941. */
  10942. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  10943. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  10944. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  10945. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10946. return fract( mul( 1.0e4, sin( mul( 17.0, value.x ).add( mul( 0.1, value.y ) ) ) ).mul( add( 0.1, abs( sin( mul( 13.0, value.y ).add( value.x ) ) ) ) ) );
  10947. } );
  10948. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  10949. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  10950. } );
  10951. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  10952. // Find the discretized derivatives of our coordinates
  10953. const maxDeriv = max$1(
  10954. length( dFdx( position.xyz ) ),
  10955. length( dFdy( position.xyz ) )
  10956. );
  10957. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  10958. // Find two nearest log-discretized noise scales
  10959. const pixScales = vec2(
  10960. exp2( floor( log2( pixScale ) ) ),
  10961. exp2( ceil( log2( pixScale ) ) )
  10962. );
  10963. // Compute alpha thresholds at our two noise scales
  10964. const alpha = vec2(
  10965. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  10966. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  10967. );
  10968. // Factor to interpolate lerp with
  10969. const lerpFactor = fract( log2( pixScale ) );
  10970. // Interpolate alpha threshold from noise at two scales
  10971. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  10972. // Pass into CDF to compute uniformly distrib threshold
  10973. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  10974. const cases = vec3(
  10975. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  10976. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  10977. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  10978. // Find our final, uniformly distributed alpha threshold (ατ)
  10979. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  10980. // Avoids ατ == 0. Could also do ατ =1-ατ
  10981. return clamp( threshold, 1.0e-6, 1.0 );
  10982. } ).setLayout( {
  10983. name: 'getAlphaHashThreshold',
  10984. type: 'float',
  10985. inputs: [
  10986. { name: 'position', type: 'vec3' }
  10987. ]
  10988. } );
  10989. /**
  10990. * Base class for all node materials.
  10991. *
  10992. * @augments Material
  10993. */
  10994. class NodeMaterial extends Material {
  10995. static get type() {
  10996. return 'NodeMaterial';
  10997. }
  10998. /**
  10999. * Represents the type of the node material.
  11000. *
  11001. * @type {String}
  11002. */
  11003. get type() {
  11004. return this.constructor.type;
  11005. }
  11006. set type( _value ) { /* */ }
  11007. /**
  11008. * Constructs a new node material.
  11009. */
  11010. constructor() {
  11011. super();
  11012. /**
  11013. * This flag can be used for type testing.
  11014. *
  11015. * @type {Boolean}
  11016. * @readonly
  11017. * @default true
  11018. */
  11019. this.isNodeMaterial = true;
  11020. /**
  11021. * Whether this material is affected by fog or not.
  11022. *
  11023. * @type {Boolean}
  11024. * @default true
  11025. */
  11026. this.fog = true;
  11027. /**
  11028. * Whether this material is affected by lights or not.
  11029. *
  11030. * @type {Boolean}
  11031. * @default false
  11032. */
  11033. this.lights = false;
  11034. /**
  11035. * Whether this material uses hardware clipping or not.
  11036. * This property is managed by the engine and should not be
  11037. * modified by apps.
  11038. *
  11039. * @type {Boolean}
  11040. * @default false
  11041. */
  11042. this.hardwareClipping = false;
  11043. /**
  11044. * Node materials which set their `lights` property to `true`
  11045. * are affected by all lights of the scene. Sometimes selective
  11046. * lighting is wanted which means only _some_ lights in the scene
  11047. * affect a material. This can be achieved by creating an instance
  11048. * of {@link module:LightsNode~LightsNode} with a list of selective
  11049. * lights and assign the node to this property.
  11050. *
  11051. * ```js
  11052. * const customLightsNode = lights( [ light1, light2 ] );
  11053. * material.lightsNode = customLightsNode;
  11054. * ```
  11055. *
  11056. * @type {LightsNode?}
  11057. * @default null
  11058. */
  11059. this.lightsNode = null;
  11060. /**
  11061. * The environment of node materials can be defined by an environment
  11062. * map assigned to the `envMap` property or by `Scene.environment`
  11063. * if the node material is a PBR material. This node property allows to overwrite
  11064. * the default behavior and define the environment with a custom node.
  11065. *
  11066. * ```js
  11067. * material.envNode = pmremTexture( renderTarget.texture );
  11068. * ```
  11069. *
  11070. * @type {Node<vec3>?}
  11071. * @default null
  11072. */
  11073. this.envNode = null;
  11074. /**
  11075. * The lighting of node materials might be influenced by ambient occlusion.
  11076. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  11077. * and the respective `aoMapIntensity`. This node property allows to overwrite
  11078. * the default and define the ambient occlusion with a custom node instead.
  11079. *
  11080. * If you don't want to overwrite the diffuse color but modify the existing
  11081. * values instead, use {@link module:MaterialNode.materialAO}.
  11082. *
  11083. * @type {Node<float>?}
  11084. * @default null
  11085. */
  11086. this.aoNode = null;
  11087. /**
  11088. * The diffuse color of node materials is by default inferred from the
  11089. * `color` and `map` properties. This node property allows to overwrite the default
  11090. * and define the diffuse color with a node instead.
  11091. *
  11092. * ```js
  11093. * material.colorNode = color( 0xff0000 ); // define red color
  11094. * ```
  11095. *
  11096. * If you don't want to overwrite the diffuse color but modify the existing
  11097. * values instead, use {@link module:MaterialNode.materialColor}.
  11098. *
  11099. * ```js
  11100. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  11101. * ```
  11102. *
  11103. * @type {Node<vec3>?}
  11104. * @default null
  11105. */
  11106. this.colorNode = null;
  11107. /**
  11108. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  11109. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  11110. * and define the normals with a node instead.
  11111. *
  11112. * If you don't want to overwrite the normals but modify the existing values instead,
  11113. * use {@link module:MaterialNode.materialNormal}.
  11114. *
  11115. * @type {Node<vec3>?}
  11116. * @default null
  11117. */
  11118. this.normalNode = null;
  11119. /**
  11120. * The opacity of node materials is by default inferred from the `opacity`
  11121. * and `alphaMap` properties. This node property allows to overwrite the default
  11122. * and define the opacity with a node instead.
  11123. *
  11124. * If you don't want to overwrite the normals but modify the existing
  11125. * value instead, use {@link module:MaterialNode.materialOpacity}.
  11126. *
  11127. * @type {Node<float>?}
  11128. * @default null
  11129. */
  11130. this.opacityNode = null;
  11131. /**
  11132. * This node can be used to to implement a variety of filter-like effects. The idea is
  11133. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  11134. * to create an arbitrary effect and then assign the node composition to this property.
  11135. * Everything behind the object using this material will now be affected by a filter.
  11136. *
  11137. * ```js
  11138. * const material = new NodeMaterial()
  11139. * material.transparent = true;
  11140. *
  11141. * // everything behind the object will be monochromatic
  11142. * material.backdropNode = viewportSharedTexture().rgb.saturation( 0 );
  11143. * ```
  11144. *
  11145. * Backdrop computations are part of the lighting so only lit materials can use this property.
  11146. *
  11147. * @type {Node<vec3>?}
  11148. * @default null
  11149. */
  11150. this.backdropNode = null;
  11151. /**
  11152. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  11153. *
  11154. * @type {Node<float>?}
  11155. * @default null
  11156. */
  11157. this.backdropAlphaNode = null;
  11158. /**
  11159. * The alpha test of node materials is by default inferred from the `alphaTest`
  11160. * property. This node property allows to overwrite the default and define the
  11161. * alpha test with a node instead.
  11162. *
  11163. * If you don't want to overwrite the alpha test but modify the existing
  11164. * value instead, use {@link module:MaterialNode.materialAlphaTest}.
  11165. *
  11166. * @type {Node<float>?}
  11167. * @default null
  11168. */
  11169. this.alphaTestNode = null;
  11170. /**
  11171. * The local vertex positions are computed based on multiple factors like the
  11172. * attribute data, morphing or skinning. This node property allows to overwrite
  11173. * the default and define local vertex positions with nodes instead.
  11174. *
  11175. * If you don't want to overwrite the vertex positions but modify the existing
  11176. * values instead, use {@link module:Position.positionLocal}.
  11177. *
  11178. *```js
  11179. * material.positionNode = positionLocal.add( displace );
  11180. * ```
  11181. *
  11182. * @type {Node<vec3>?}
  11183. * @default null
  11184. */
  11185. this.positionNode = null;
  11186. /**
  11187. * This node property is intended for logic which modifies geometry data once or per animation step.
  11188. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  11189. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  11190. * can be implemented.
  11191. *
  11192. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  11193. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  11194. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  11195. * eventually assigned to `geometryNode`.
  11196. *
  11197. * @type {Function}
  11198. * @default null
  11199. */
  11200. this.geometryNode = null;
  11201. /**
  11202. * Allows to overwrite depth values in the fragment shader.
  11203. *
  11204. * @type {Node<float>?}
  11205. * @default null
  11206. */
  11207. this.depthNode = null;
  11208. /**
  11209. * Allows to overwrite the position used for shadow map rendering which
  11210. * is by default {@link module:Position.positionWorld}, the vertex position
  11211. * in world space.
  11212. *
  11213. * @type {Node<float>?}
  11214. * @default null
  11215. */
  11216. this.shadowPositionNode = null;
  11217. /**
  11218. * This node can be used to influence how an object using this node material
  11219. * receive shadows.
  11220. *
  11221. * ```js
  11222. * const totalShadows = float( 1 ).toVar();
  11223. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  11224. * totalShadows.mulAssign( shadow );
  11225. * //return float( 1 ); // bypass received shadows
  11226. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  11227. * } );
  11228. *
  11229. * @type {Node<vec4>?}
  11230. * @default null
  11231. */
  11232. this.receivedShadowNode = null;
  11233. /**
  11234. * This node can be used to influence how an object using this node material
  11235. * casts shadows. To apply a color to shadows, you can simply do:
  11236. *
  11237. * ```js
  11238. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  11239. * ```
  11240. *
  11241. * Which can be nice to fake colored shadows of semi-transparent objects. It
  11242. * is also common to use the property with `Fn` function so checks are performed
  11243. * per fragment.
  11244. *
  11245. * ```js
  11246. * materialCustomShadow.castShadowNode = Fn( () => {
  11247. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  11248. * return materialColor;
  11249. * } )();
  11250. * ```
  11251. *
  11252. * @type {Node<vec4>?}
  11253. * @default null
  11254. */
  11255. this.castShadowNode = null;
  11256. /**
  11257. * This node can be used to define the final output of the material.
  11258. *
  11259. * TODO: Explain the differences to `fragmentNode`.
  11260. *
  11261. * @type {Node<vec4>?}
  11262. * @default null
  11263. */
  11264. this.outputNode = null;
  11265. /**
  11266. * MRT configuration is done on renderer or pass level. This node allows to
  11267. * overwrite what values are written into MRT targets on material level. This
  11268. * can be useful for implementing selective FX features that should only affect
  11269. * specific objects.
  11270. *
  11271. * @type {MRTNode?}
  11272. * @default null
  11273. */
  11274. this.mrtNode = null;
  11275. /**
  11276. * This node property can be used if you need complete freedom in implementing
  11277. * the fragment shader. Assigning a node will replace the built-in material
  11278. * logic used in the fragment stage.
  11279. *
  11280. * @type {Node<vec4>?}
  11281. * @default null
  11282. */
  11283. this.fragmentNode = null;
  11284. /**
  11285. * This node property can be used if you need complete freedom in implementing
  11286. * the vertex shader. Assigning a node will replace the built-in material logic
  11287. * used in the vertex stage.
  11288. *
  11289. * @type {Node<vec4>?}
  11290. * @default null
  11291. */
  11292. this.vertexNode = null;
  11293. }
  11294. /**
  11295. * Allows to define a custom cache key that influence the material key computation
  11296. * for render objects.
  11297. *
  11298. * @return {String} The custom cache key.
  11299. */
  11300. customProgramCacheKey() {
  11301. return this.type + getCacheKey$1( this );
  11302. }
  11303. /**
  11304. * Builds this material with the given node builder.
  11305. *
  11306. * @param {NodeBuilder} builder - The current node builder.
  11307. */
  11308. build( builder ) {
  11309. this.setup( builder );
  11310. }
  11311. /**
  11312. * Setups a node material observer with the given builder.
  11313. *
  11314. * @param {NodeBuilder} builder - The current node builder.
  11315. * @return {NodeMaterialObserver} The node material observer.
  11316. */
  11317. setupObserver( builder ) {
  11318. return new NodeMaterialObserver( builder );
  11319. }
  11320. /**
  11321. * Setups the vertex and fragment stage of this node material.
  11322. *
  11323. * @param {NodeBuilder} builder - The current node builder.
  11324. */
  11325. setup( builder ) {
  11326. builder.context.setupNormal = () => this.setupNormal( builder );
  11327. builder.context.setupPositionView = () => this.setupPositionView( builder );
  11328. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  11329. const renderer = builder.renderer;
  11330. const renderTarget = renderer.getRenderTarget();
  11331. // < VERTEX STAGE >
  11332. builder.addStack();
  11333. const vertexNode = this.vertexNode || this.setupVertex( builder );
  11334. builder.stack.outputNode = vertexNode;
  11335. this.setupHardwareClipping( builder );
  11336. if ( this.geometryNode !== null ) {
  11337. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  11338. }
  11339. builder.addFlow( 'vertex', builder.removeStack() );
  11340. // < FRAGMENT STAGE >
  11341. builder.addStack();
  11342. let resultNode;
  11343. const clippingNode = this.setupClipping( builder );
  11344. if ( this.depthWrite === true || this.depthTest === true ) {
  11345. // only write depth if depth buffer is configured
  11346. if ( renderTarget !== null ) {
  11347. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  11348. } else {
  11349. if ( renderer.depth === true ) this.setupDepth( builder );
  11350. }
  11351. }
  11352. if ( this.fragmentNode === null ) {
  11353. this.setupDiffuseColor( builder );
  11354. this.setupVariants( builder );
  11355. const outgoingLightNode = this.setupLighting( builder );
  11356. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  11357. // force unsigned floats - useful for RenderTargets
  11358. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  11359. resultNode = this.setupOutput( builder, basicOutput );
  11360. // OUTPUT NODE
  11361. output.assign( resultNode );
  11362. //
  11363. if ( this.outputNode !== null ) resultNode = this.outputNode;
  11364. // MRT
  11365. if ( renderTarget !== null ) {
  11366. const mrt = renderer.getMRT();
  11367. const materialMRT = this.mrtNode;
  11368. if ( mrt !== null ) {
  11369. resultNode = mrt;
  11370. if ( materialMRT !== null ) {
  11371. resultNode = mrt.merge( materialMRT );
  11372. }
  11373. } else if ( materialMRT !== null ) {
  11374. resultNode = materialMRT;
  11375. }
  11376. }
  11377. } else {
  11378. let fragmentNode = this.fragmentNode;
  11379. if ( fragmentNode.isOutputStructNode !== true ) {
  11380. fragmentNode = vec4( fragmentNode );
  11381. }
  11382. resultNode = this.setupOutput( builder, fragmentNode );
  11383. }
  11384. builder.stack.outputNode = resultNode;
  11385. builder.addFlow( 'fragment', builder.removeStack() );
  11386. // < MONITOR >
  11387. builder.monitor = this.setupObserver( builder );
  11388. }
  11389. /**
  11390. * Setups the clipping node.
  11391. *
  11392. * @param {NodeBuilder} builder - The current node builder.
  11393. * @return {ClippingNode} The clipping node.
  11394. */
  11395. setupClipping( builder ) {
  11396. if ( builder.clippingContext === null ) return null;
  11397. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  11398. let result = null;
  11399. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  11400. const samples = builder.renderer.samples;
  11401. if ( this.alphaToCoverage && samples > 1 ) {
  11402. // to be added to flow when the color/alpha value has been determined
  11403. result = clippingAlpha();
  11404. } else {
  11405. builder.stack.add( clipping() );
  11406. }
  11407. }
  11408. return result;
  11409. }
  11410. /**
  11411. * Setups the hardware clipping if available on the current device.
  11412. *
  11413. * @param {NodeBuilder} builder - The current node builder.
  11414. */
  11415. setupHardwareClipping( builder ) {
  11416. this.hardwareClipping = false;
  11417. if ( builder.clippingContext === null ) return;
  11418. const candidateCount = builder.clippingContext.unionPlanes.length;
  11419. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  11420. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  11421. builder.stack.add( hardwareClipping() );
  11422. this.hardwareClipping = true;
  11423. }
  11424. return;
  11425. }
  11426. /**
  11427. * Setups the depth of this material.
  11428. *
  11429. * @param {NodeBuilder} builder - The current node builder.
  11430. */
  11431. setupDepth( builder ) {
  11432. const { renderer, camera } = builder;
  11433. // Depth
  11434. let depthNode = this.depthNode;
  11435. if ( depthNode === null ) {
  11436. const mrt = renderer.getMRT();
  11437. if ( mrt && mrt.has( 'depth' ) ) {
  11438. depthNode = mrt.get( 'depth' );
  11439. } else if ( renderer.logarithmicDepthBuffer === true ) {
  11440. if ( camera.isPerspectiveCamera ) {
  11441. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  11442. } else {
  11443. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  11444. }
  11445. }
  11446. }
  11447. if ( depthNode !== null ) {
  11448. depth.assign( depthNode ).append();
  11449. }
  11450. }
  11451. /**
  11452. * Setups the position node in view space. This method exists
  11453. * so derived node materials can modify the implementation e.g. sprite materials.
  11454. *
  11455. * @param {NodeBuilder} builder - The current node builder.
  11456. * @return {Node<vec3>} The position in view space.
  11457. */
  11458. setupPositionView( /*builder*/ ) {
  11459. return modelViewMatrix.mul( positionLocal ).xyz;
  11460. }
  11461. /**
  11462. * Setups the position in clip space.
  11463. *
  11464. * @param {NodeBuilder} builder - The current node builder.
  11465. * @return {Node<vec4>} The position in view space.
  11466. */
  11467. setupModelViewProjection( /*builder*/ ) {
  11468. return cameraProjectionMatrix.mul( positionView );
  11469. }
  11470. /**
  11471. * Setups the logic for the vertex stage.
  11472. *
  11473. * @param {NodeBuilder} builder - The current node builder.
  11474. * @return {Node<vec4>} The position in clip space.
  11475. */
  11476. setupVertex( builder ) {
  11477. builder.addStack();
  11478. this.setupPosition( builder );
  11479. builder.context.vertex = builder.removeStack();
  11480. return modelViewProjection;
  11481. }
  11482. /**
  11483. * Setups the computation of the position in local space.
  11484. *
  11485. * @param {NodeBuilder} builder - The current node builder.
  11486. * @return {Node<vec3>} The position in local space.
  11487. */
  11488. setupPosition( builder ) {
  11489. const { object, geometry } = builder;
  11490. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  11491. morphReference( object ).append();
  11492. }
  11493. if ( object.isSkinnedMesh === true ) {
  11494. skinningReference( object ).append();
  11495. }
  11496. if ( this.displacementMap ) {
  11497. const displacementMap = materialReference( 'displacementMap', 'texture' );
  11498. const displacementScale = materialReference( 'displacementScale', 'float' );
  11499. const displacementBias = materialReference( 'displacementBias', 'float' );
  11500. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  11501. }
  11502. if ( object.isBatchedMesh ) {
  11503. batch( object ).append();
  11504. }
  11505. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  11506. instancedMesh( object ).append();
  11507. }
  11508. if ( this.positionNode !== null ) {
  11509. positionLocal.assign( this.positionNode.context( { isPositionNodeInput: true } ) );
  11510. }
  11511. return positionLocal;
  11512. }
  11513. /**
  11514. * Setups the computation of the material's diffuse color.
  11515. *
  11516. * @param {NodeBuilder} builder - The current node builder.
  11517. * @param {BufferGeometry} geometry - The geometry.
  11518. */
  11519. setupDiffuseColor( { object, geometry } ) {
  11520. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  11521. // VERTEX COLORS
  11522. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  11523. colorNode = vec4( colorNode.xyz.mul( attribute( 'color', 'vec3' ) ), colorNode.a );
  11524. }
  11525. // Instanced colors
  11526. if ( object.instanceColor ) {
  11527. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  11528. colorNode = instanceColor.mul( colorNode );
  11529. }
  11530. if ( object.isBatchedMesh && object._colorsTexture ) {
  11531. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  11532. colorNode = batchColor.mul( colorNode );
  11533. }
  11534. // COLOR
  11535. diffuseColor.assign( colorNode );
  11536. // OPACITY
  11537. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  11538. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  11539. // ALPHA TEST
  11540. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  11541. const alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  11542. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  11543. }
  11544. // ALPHA HASH
  11545. if ( this.alphaHash === true ) {
  11546. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  11547. }
  11548. if ( this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false ) {
  11549. diffuseColor.a.assign( 1.0 );
  11550. }
  11551. }
  11552. /**
  11553. * Abstract interface method that can be implemented by derived materials
  11554. * to setup material-specific node variables.
  11555. *
  11556. * @abstract
  11557. * @param {NodeBuilder} builder - The current node builder.
  11558. */
  11559. setupVariants( /*builder*/ ) {
  11560. // Interface function.
  11561. }
  11562. /**
  11563. * Setups the outgoing light node variable
  11564. *
  11565. * @return {Node<vec3>} The outgoing light node.
  11566. */
  11567. setupOutgoingLight() {
  11568. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  11569. }
  11570. /**
  11571. * Setups the normal node from the material.
  11572. *
  11573. * @return {Node<vec3>} The normal node.
  11574. */
  11575. setupNormal() {
  11576. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  11577. }
  11578. /**
  11579. * Setups the environment node from the material.
  11580. *
  11581. * @param {NodeBuilder} builder - The current node builder.
  11582. * @return {Node<vec4>} The environment node.
  11583. */
  11584. setupEnvironment( /*builder*/ ) {
  11585. let node = null;
  11586. if ( this.envNode ) {
  11587. node = this.envNode;
  11588. } else if ( this.envMap ) {
  11589. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  11590. }
  11591. return node;
  11592. }
  11593. /**
  11594. * Setups the light map node from the material.
  11595. *
  11596. * @param {NodeBuilder} builder - The current node builder.
  11597. * @return {Node<vec3>} The light map node.
  11598. */
  11599. setupLightMap( builder ) {
  11600. let node = null;
  11601. if ( builder.material.lightMap ) {
  11602. node = new IrradianceNode( materialLightMap );
  11603. }
  11604. return node;
  11605. }
  11606. /**
  11607. * Setups the lights node based on the scene, environment and material.
  11608. *
  11609. * @param {NodeBuilder} builder - The current node builder.
  11610. * @return {LightsNode} The lights node.
  11611. */
  11612. setupLights( builder ) {
  11613. const materialLightsNode = [];
  11614. //
  11615. const envNode = this.setupEnvironment( builder );
  11616. if ( envNode && envNode.isLightingNode ) {
  11617. materialLightsNode.push( envNode );
  11618. }
  11619. const lightMapNode = this.setupLightMap( builder );
  11620. if ( lightMapNode && lightMapNode.isLightingNode ) {
  11621. materialLightsNode.push( lightMapNode );
  11622. }
  11623. if ( this.aoNode !== null || builder.material.aoMap ) {
  11624. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  11625. materialLightsNode.push( new AONode( aoNode ) );
  11626. }
  11627. let lightsN = this.lightsNode || builder.lightsNode;
  11628. if ( materialLightsNode.length > 0 ) {
  11629. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  11630. }
  11631. return lightsN;
  11632. }
  11633. /**
  11634. * This method should be implemented by most derived materials
  11635. * since it defines the material's lighting model.
  11636. *
  11637. * @abstract
  11638. * @param {NodeBuilder} builder - The current node builder.
  11639. * @return {LightingModel} The lighting model.
  11640. */
  11641. setupLightingModel( /*builder*/ ) {
  11642. // Interface function.
  11643. }
  11644. /**
  11645. * Setups the outgoing light node.
  11646. *
  11647. * @param {NodeBuilder} builder - The current node builder.
  11648. * @return {Node<vec3>} The outgoing light node.
  11649. */
  11650. setupLighting( builder ) {
  11651. const { material } = builder;
  11652. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  11653. // OUTGOING LIGHT
  11654. const lights = this.lights === true || this.lightsNode !== null;
  11655. const lightsNode = lights ? this.setupLights( builder ) : null;
  11656. let outgoingLightNode = this.setupOutgoingLight( builder );
  11657. if ( lightsNode && lightsNode.getScope().hasLights ) {
  11658. const lightingModel = this.setupLightingModel( builder );
  11659. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  11660. } else if ( backdropNode !== null ) {
  11661. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  11662. }
  11663. // EMISSIVE
  11664. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  11665. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  11666. outgoingLightNode = outgoingLightNode.add( emissive );
  11667. }
  11668. return outgoingLightNode;
  11669. }
  11670. /**
  11671. * Setups the output node.
  11672. *
  11673. * @param {NodeBuilder} builder - The current node builder.
  11674. * @param {Node<vec4>} outputNode - The existing output node.
  11675. * @return {Node<vec4>} The output node.
  11676. */
  11677. setupOutput( builder, outputNode ) {
  11678. // FOG
  11679. if ( this.fog === true ) {
  11680. const fogNode = builder.fogNode;
  11681. if ( fogNode ) {
  11682. output.assign( outputNode );
  11683. outputNode = vec4( fogNode );
  11684. }
  11685. }
  11686. return outputNode;
  11687. }
  11688. /**
  11689. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  11690. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  11691. * defining all material properties of the classic type in the node type.
  11692. *
  11693. * @param {Material} material - The material to copy properties with their values to this node material.
  11694. */
  11695. setDefaultValues( material ) {
  11696. // This approach is to reuse the native refreshUniforms*
  11697. // and turn available the use of features like transmission and environment in core
  11698. for ( const property in material ) {
  11699. const value = material[ property ];
  11700. if ( this[ property ] === undefined ) {
  11701. this[ property ] = value;
  11702. if ( value && value.clone ) this[ property ] = value.clone();
  11703. }
  11704. }
  11705. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  11706. for ( const key in descriptors ) {
  11707. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  11708. descriptors[ key ].get !== undefined ) {
  11709. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  11710. }
  11711. }
  11712. }
  11713. /**
  11714. * Serializes this material to JSON.
  11715. *
  11716. * @param {(Object|String)?} meta - The meta information for serialization.
  11717. * @return {Object} The serialized node.
  11718. */
  11719. toJSON( meta ) {
  11720. const isRoot = ( meta === undefined || typeof meta === 'string' );
  11721. if ( isRoot ) {
  11722. meta = {
  11723. textures: {},
  11724. images: {},
  11725. nodes: {}
  11726. };
  11727. }
  11728. const data = Material.prototype.toJSON.call( this, meta );
  11729. const nodeChildren = getNodeChildren( this );
  11730. data.inputNodes = {};
  11731. for ( const { property, childNode } of nodeChildren ) {
  11732. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  11733. }
  11734. // TODO: Copied from Object3D.toJSON
  11735. function extractFromCache( cache ) {
  11736. const values = [];
  11737. for ( const key in cache ) {
  11738. const data = cache[ key ];
  11739. delete data.metadata;
  11740. values.push( data );
  11741. }
  11742. return values;
  11743. }
  11744. if ( isRoot ) {
  11745. const textures = extractFromCache( meta.textures );
  11746. const images = extractFromCache( meta.images );
  11747. const nodes = extractFromCache( meta.nodes );
  11748. if ( textures.length > 0 ) data.textures = textures;
  11749. if ( images.length > 0 ) data.images = images;
  11750. if ( nodes.length > 0 ) data.nodes = nodes;
  11751. }
  11752. return data;
  11753. }
  11754. /**
  11755. * Copies the properties of the given node material to this instance.
  11756. *
  11757. * @param {NodeMaterial} source - The material to copy.
  11758. * @return {NodeMaterial} A reference to this node material.
  11759. */
  11760. copy( source ) {
  11761. this.lightsNode = source.lightsNode;
  11762. this.envNode = source.envNode;
  11763. this.colorNode = source.colorNode;
  11764. this.normalNode = source.normalNode;
  11765. this.opacityNode = source.opacityNode;
  11766. this.backdropNode = source.backdropNode;
  11767. this.backdropAlphaNode = source.backdropAlphaNode;
  11768. this.alphaTestNode = source.alphaTestNode;
  11769. this.positionNode = source.positionNode;
  11770. this.geometryNode = source.geometryNode;
  11771. this.depthNode = source.depthNode;
  11772. this.shadowPositionNode = source.shadowPositionNode;
  11773. this.receivedShadowNode = source.receivedShadowNode;
  11774. this.castShadowNode = source.castShadowNode;
  11775. this.outputNode = source.outputNode;
  11776. this.mrtNode = source.mrtNode;
  11777. this.fragmentNode = source.fragmentNode;
  11778. this.vertexNode = source.vertexNode;
  11779. return super.copy( source );
  11780. }
  11781. }
  11782. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  11783. /**
  11784. * Node material version of `LineBasicMaterial`.
  11785. *
  11786. * @augments NodeMaterial
  11787. */
  11788. class LineBasicNodeMaterial extends NodeMaterial {
  11789. static get type() {
  11790. return 'LineBasicNodeMaterial';
  11791. }
  11792. /**
  11793. * Constructs a new line basic node material.
  11794. *
  11795. * @param {Object?} parameters - The configuration parameter.
  11796. */
  11797. constructor( parameters ) {
  11798. super();
  11799. /**
  11800. * This flag can be used for type testing.
  11801. *
  11802. * @type {Boolean}
  11803. * @readonly
  11804. * @default true
  11805. */
  11806. this.isLineBasicNodeMaterial = true;
  11807. this.setDefaultValues( _defaultValues$d );
  11808. this.setValues( parameters );
  11809. }
  11810. }
  11811. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  11812. /**
  11813. * Node material version of `LineDashedMaterial`.
  11814. *
  11815. * @augments NodeMaterial
  11816. */
  11817. class LineDashedNodeMaterial extends NodeMaterial {
  11818. static get type() {
  11819. return 'LineDashedNodeMaterial';
  11820. }
  11821. /**
  11822. * Constructs a new line dashed node material.
  11823. *
  11824. * @param {Object?} parameters - The configuration parameter.
  11825. */
  11826. constructor( parameters ) {
  11827. super();
  11828. /**
  11829. * This flag can be used for type testing.
  11830. *
  11831. * @type {Boolean}
  11832. * @readonly
  11833. * @default true
  11834. */
  11835. this.isLineDashedNodeMaterial = true;
  11836. this.setDefaultValues( _defaultValues$c );
  11837. /**
  11838. * The dash offset.
  11839. *
  11840. * @type {Number}
  11841. * @default 0
  11842. */
  11843. this.dashOffset = 0;
  11844. /**
  11845. * The offset of dash materials is by default inferred from the `dashOffset`
  11846. * property. This node property allows to overwrite the default
  11847. * and define the offset with a node instead.
  11848. *
  11849. * If you don't want to overwrite the offset but modify the existing
  11850. * value instead, use {@link module:MaterialNode.materialLineDashOffset}.
  11851. *
  11852. * @type {Node<float>?}
  11853. * @default null
  11854. */
  11855. this.offsetNode = null;
  11856. /**
  11857. * The scale of dash materials is by default inferred from the `scale`
  11858. * property. This node property allows to overwrite the default
  11859. * and define the scale with a node instead.
  11860. *
  11861. * If you don't want to overwrite the scale but modify the existing
  11862. * value instead, use {@link module:MaterialNode.materialLineScale}.
  11863. *
  11864. * @type {Node<float>?}
  11865. * @default null
  11866. */
  11867. this.dashScaleNode = null;
  11868. /**
  11869. * The dash size of dash materials is by default inferred from the `dashSize`
  11870. * property. This node property allows to overwrite the default
  11871. * and define the dash size with a node instead.
  11872. *
  11873. * If you don't want to overwrite the dash size but modify the existing
  11874. * value instead, use {@link module:MaterialNode.materialLineDashSize}.
  11875. *
  11876. * @type {Node<float>?}
  11877. * @default null
  11878. */
  11879. this.dashSizeNode = null;
  11880. /**
  11881. * The gap size of dash materials is by default inferred from the `gapSize`
  11882. * property. This node property allows to overwrite the default
  11883. * and define the gap size with a node instead.
  11884. *
  11885. * If you don't want to overwrite the gap size but modify the existing
  11886. * value instead, use {@link module:MaterialNode.materialLineGapSize}.
  11887. *
  11888. * @type {Node<float>?}
  11889. * @default null
  11890. */
  11891. this.gapSizeNode = null;
  11892. this.setValues( parameters );
  11893. }
  11894. /**
  11895. * Setups the dash specific node variables.
  11896. *
  11897. * @param {NodeBuilder} builder - The current node builder.
  11898. */
  11899. setupVariants( /* builder */ ) {
  11900. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  11901. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  11902. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  11903. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  11904. dashSize.assign( dashSizeNode );
  11905. gapSize.assign( gapSizeNode );
  11906. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  11907. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  11908. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  11909. }
  11910. }
  11911. /** @module ViewportSharedTextureNode **/
  11912. let _sharedFramebuffer = null;
  11913. /**
  11914. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  11915. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  11916. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  11917. *
  11918. * @augments module:ViewportTextureNode~ViewportTextureNode
  11919. */
  11920. class ViewportSharedTextureNode extends ViewportTextureNode {
  11921. static get type() {
  11922. return 'ViewportSharedTextureNode';
  11923. }
  11924. /**
  11925. * Constructs a new viewport shared texture node.
  11926. *
  11927. * @param {Node} [uvNode=screenUV] - The uv node.
  11928. * @param {Node?} [levelNode=null] - The level node.
  11929. */
  11930. constructor( uvNode = screenUV, levelNode = null ) {
  11931. if ( _sharedFramebuffer === null ) {
  11932. _sharedFramebuffer = new FramebufferTexture();
  11933. }
  11934. super( uvNode, levelNode, _sharedFramebuffer );
  11935. }
  11936. updateReference() {
  11937. return this;
  11938. }
  11939. }
  11940. /**
  11941. * TSL function for creating a shared viewport texture node.
  11942. *
  11943. * @function
  11944. * @param {Node} [uvNode=screenUV] - The uv node.
  11945. * @param {Node?} [levelNode=null] - The level node.
  11946. * @returns {ViewportSharedTextureNode}
  11947. */
  11948. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode );
  11949. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  11950. /**
  11951. * This node material can be used to render lines with a size larger than one
  11952. * by representing them as instanced meshes.
  11953. *
  11954. * @augments NodeMaterial
  11955. */
  11956. class Line2NodeMaterial extends NodeMaterial {
  11957. static get type() {
  11958. return 'Line2NodeMaterial';
  11959. }
  11960. /**
  11961. * Constructs a new node material for wide line rendering.
  11962. *
  11963. * @param {Object?} parameters - The configuration parameter.
  11964. */
  11965. constructor( parameters = {} ) {
  11966. super();
  11967. /**
  11968. * This flag can be used for type testing.
  11969. *
  11970. * @type {Boolean}
  11971. * @readonly
  11972. * @default true
  11973. */
  11974. this.isLine2NodeMaterial = true;
  11975. this.setDefaultValues( _defaultValues$b );
  11976. /**
  11977. * Whether vertex colors should be used or not.
  11978. *
  11979. * @type {Boolean}
  11980. * @default false
  11981. */
  11982. this.useColor = parameters.vertexColors;
  11983. /**
  11984. * The dash offset.
  11985. *
  11986. * @type {Number}
  11987. * @default 0
  11988. */
  11989. this.dashOffset = 0;
  11990. /**
  11991. * The line width.
  11992. *
  11993. * @type {Number}
  11994. * @default 0
  11995. */
  11996. this.lineWidth = 1;
  11997. /**
  11998. * Defines the lines color.
  11999. *
  12000. * @type {Node<vec3>?}
  12001. * @default null
  12002. */
  12003. this.lineColorNode = null;
  12004. /**
  12005. * Defines the offset.
  12006. *
  12007. * @type {Node<float>?}
  12008. * @default null
  12009. */
  12010. this.offsetNode = null;
  12011. /**
  12012. * Defines the dash scale.
  12013. *
  12014. * @type {Node<float>?}
  12015. * @default null
  12016. */
  12017. this.dashScaleNode = null;
  12018. /**
  12019. * Defines the dash size.
  12020. *
  12021. * @type {Node<float>?}
  12022. * @default null
  12023. */
  12024. this.dashSizeNode = null;
  12025. /**
  12026. * Defines the gap size.
  12027. *
  12028. * @type {Node<float>?}
  12029. * @default null
  12030. */
  12031. this.gapSizeNode = null;
  12032. /**
  12033. * Blending is set to `NoBlending` since transparency
  12034. * is not supported, yet.
  12035. *
  12036. * @type {Number}
  12037. * @default 0
  12038. */
  12039. this.blending = NoBlending;
  12040. this._useDash = parameters.dashed;
  12041. this._useAlphaToCoverage = true;
  12042. this._useWorldUnits = false;
  12043. this.setValues( parameters );
  12044. }
  12045. /**
  12046. * Setups the vertex and fragment stage of this node material.
  12047. *
  12048. * @param {NodeBuilder} builder - The current node builder.
  12049. */
  12050. setup( builder ) {
  12051. const { renderer } = builder;
  12052. const useAlphaToCoverage = this._useAlphaToCoverage;
  12053. const useColor = this.useColor;
  12054. const useDash = this._useDash;
  12055. const useWorldUnits = this._useWorldUnits;
  12056. const trimSegment = Fn( ( { start, end } ) => {
  12057. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  12058. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  12059. const nearEstimate = b.mul( - 0.5 ).div( a );
  12060. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  12061. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  12062. } ).setLayout( {
  12063. name: 'trimSegment',
  12064. type: 'vec4',
  12065. inputs: [
  12066. { name: 'start', type: 'vec4' },
  12067. { name: 'end', type: 'vec4' }
  12068. ]
  12069. } );
  12070. this.vertexNode = Fn( () => {
  12071. const instanceStart = attribute( 'instanceStart' );
  12072. const instanceEnd = attribute( 'instanceEnd' );
  12073. // camera space
  12074. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  12075. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  12076. if ( useDash ) {
  12077. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  12078. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  12079. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  12080. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  12081. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  12082. lineDistance = lineDistance.add( offsetNode );
  12083. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  12084. }
  12085. if ( useWorldUnits ) {
  12086. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  12087. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  12088. }
  12089. const aspect = viewport.z.div( viewport.w );
  12090. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  12091. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  12092. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  12093. // perhaps there is a more elegant solution -- WestLangley
  12094. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( - 1.0 ); // 4th entry in the 3rd column
  12095. If( perspective, () => {
  12096. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  12097. end.assign( trimSegment( { start: start, end: end } ) );
  12098. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  12099. start.assign( trimSegment( { start: end, end: start } ) );
  12100. } );
  12101. } );
  12102. // clip space
  12103. const clipStart = cameraProjectionMatrix.mul( start );
  12104. const clipEnd = cameraProjectionMatrix.mul( end );
  12105. // ndc space
  12106. const ndcStart = clipStart.xyz.div( clipStart.w );
  12107. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  12108. // direction
  12109. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  12110. // account for clip-space aspect ratio
  12111. dir.x.assign( dir.x.mul( aspect ) );
  12112. dir.assign( dir.normalize() );
  12113. const clip = vec4().toVar();
  12114. if ( useWorldUnits ) {
  12115. // get the offset direction as perpendicular to the view vector
  12116. const worldDir = end.xyz.sub( start.xyz ).normalize();
  12117. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  12118. const worldUp = worldDir.cross( tmpFwd ).normalize();
  12119. const worldFwd = worldDir.cross( worldUp );
  12120. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  12121. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  12122. // height offset
  12123. const hw = materialLineWidth.mul( 0.5 );
  12124. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  12125. // don't extend the line if we're rendering dashes because we
  12126. // won't be rendering the endcaps
  12127. if ( ! useDash ) {
  12128. // cap extension
  12129. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  12130. // add width to the box
  12131. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  12132. // endcaps
  12133. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  12134. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  12135. } );
  12136. }
  12137. // project the worldpos
  12138. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  12139. // shift the depth of the projected points so the line
  12140. // segments overlap neatly
  12141. const clipPose = vec3().toVar();
  12142. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  12143. clip.z.assign( clipPose.z.mul( clip.w ) );
  12144. } else {
  12145. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  12146. // undo aspect ratio adjustment
  12147. dir.x.assign( dir.x.div( aspect ) );
  12148. offset.x.assign( offset.x.div( aspect ) );
  12149. // sign flip
  12150. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  12151. // endcaps
  12152. If( positionGeometry.y.lessThan( 0.0 ), () => {
  12153. offset.assign( offset.sub( dir ) );
  12154. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  12155. offset.assign( offset.add( dir ) );
  12156. } );
  12157. // adjust for linewidth
  12158. offset.assign( offset.mul( materialLineWidth ) );
  12159. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  12160. offset.assign( offset.div( viewport.w ) );
  12161. // select end
  12162. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  12163. // back to clip space
  12164. offset.assign( offset.mul( clip.w ) );
  12165. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  12166. }
  12167. return clip;
  12168. } )();
  12169. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  12170. const p13 = p1.sub( p3 );
  12171. const p43 = p4.sub( p3 );
  12172. const p21 = p2.sub( p1 );
  12173. const d1343 = p13.dot( p43 );
  12174. const d4321 = p43.dot( p21 );
  12175. const d1321 = p13.dot( p21 );
  12176. const d4343 = p43.dot( p43 );
  12177. const d2121 = p21.dot( p21 );
  12178. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  12179. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  12180. const mua = numer.div( denom ).clamp();
  12181. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  12182. return vec2( mua, mub );
  12183. } );
  12184. this.colorNode = Fn( () => {
  12185. const vUv = uv();
  12186. if ( useDash ) {
  12187. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  12188. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  12189. dashSize.assign( dashSizeNode );
  12190. gapSize.assign( gapSizeNode );
  12191. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  12192. vUv.y.lessThan( - 1.0 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  12193. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  12194. }
  12195. const alpha = float( 1 ).toVar( 'alpha' );
  12196. if ( useWorldUnits ) {
  12197. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  12198. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  12199. // Find the closest points on the view ray and the line segment
  12200. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  12201. const lineDir = worldEnd.sub( worldStart );
  12202. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  12203. const p1 = worldStart.add( lineDir.mul( params.x ) );
  12204. const p2 = rayEnd.mul( params.y );
  12205. const delta = p1.sub( p2 );
  12206. const len = delta.length();
  12207. const norm = len.div( materialLineWidth );
  12208. if ( ! useDash ) {
  12209. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12210. const dnorm = norm.fwidth();
  12211. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  12212. } else {
  12213. norm.greaterThan( 0.5 ).discard();
  12214. }
  12215. }
  12216. } else {
  12217. // round endcaps
  12218. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  12219. const a = vUv.x;
  12220. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12221. const len2 = a.mul( a ).add( b.mul( b ) );
  12222. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  12223. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12224. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  12225. } );
  12226. } else {
  12227. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  12228. const a = vUv.x;
  12229. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  12230. const len2 = a.mul( a ).add( b.mul( b ) );
  12231. len2.greaterThan( 1.0 ).discard();
  12232. } );
  12233. }
  12234. }
  12235. let lineColorNode;
  12236. if ( this.lineColorNode ) {
  12237. lineColorNode = this.lineColorNode;
  12238. } else {
  12239. if ( useColor ) {
  12240. const instanceColorStart = attribute( 'instanceColorStart' );
  12241. const instanceColorEnd = attribute( 'instanceColorEnd' );
  12242. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  12243. lineColorNode = instanceColor.mul( materialColor );
  12244. } else {
  12245. lineColorNode = materialColor;
  12246. }
  12247. }
  12248. return vec4( lineColorNode, alpha );
  12249. } )();
  12250. if ( this.transparent ) {
  12251. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12252. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  12253. }
  12254. super.setup( builder );
  12255. }
  12256. /**
  12257. * Whether the lines should sized in world units or not.
  12258. * When set to `false` the unit is pixel.
  12259. *
  12260. * @type {Boolean}
  12261. * @default false
  12262. */
  12263. get worldUnits() {
  12264. return this._useWorldUnits;
  12265. }
  12266. set worldUnits( value ) {
  12267. if ( this._useWorldUnits !== value ) {
  12268. this._useWorldUnits = value;
  12269. this.needsUpdate = true;
  12270. }
  12271. }
  12272. /**
  12273. * Whether the lines should be dashed or not.
  12274. *
  12275. * @type {Boolean}
  12276. * @default false
  12277. */
  12278. get dashed() {
  12279. return this._useDash;
  12280. }
  12281. set dashed( value ) {
  12282. if ( this._useDash !== value ) {
  12283. this._useDash = value;
  12284. this.needsUpdate = true;
  12285. }
  12286. }
  12287. /**
  12288. * Whether alpha to coverage should be used or not.
  12289. *
  12290. * @type {Boolean}
  12291. * @default true
  12292. */
  12293. get alphaToCoverage() {
  12294. return this._useAlphaToCoverage;
  12295. }
  12296. set alphaToCoverage( value ) {
  12297. if ( this._useAlphaToCoverage !== value ) {
  12298. this._useAlphaToCoverage = value;
  12299. this.needsUpdate = true;
  12300. }
  12301. }
  12302. }
  12303. /** @module Packing **/
  12304. /**
  12305. * Packs a direction vector into a color value.
  12306. *
  12307. * @method
  12308. * @param {Node<vec3>} node - The direction to pack.
  12309. * @return {Node<vec3>} The color.
  12310. */
  12311. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  12312. /**
  12313. * Unpacks a color value into a direction vector.
  12314. *
  12315. * @method
  12316. * @param {Node<vec3>} node - The color to unpack.
  12317. * @return {Node<vec3>} The direction.
  12318. */
  12319. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  12320. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  12321. /**
  12322. * Node material version of `MeshNormalMaterial`.
  12323. *
  12324. * @augments NodeMaterial
  12325. */
  12326. class MeshNormalNodeMaterial extends NodeMaterial {
  12327. static get type() {
  12328. return 'MeshNormalNodeMaterial';
  12329. }
  12330. /**
  12331. * Constructs a new mesh normal node material.
  12332. *
  12333. * @param {Object?} parameters - The configuration parameter.
  12334. */
  12335. constructor( parameters ) {
  12336. super();
  12337. /**
  12338. * This flag can be used for type testing.
  12339. *
  12340. * @type {Boolean}
  12341. * @readonly
  12342. * @default true
  12343. */
  12344. this.isMeshNormalNodeMaterial = true;
  12345. this.setDefaultValues( _defaultValues$a );
  12346. this.setValues( parameters );
  12347. }
  12348. /**
  12349. * Overwrites the default implementation by computing the diffuse color
  12350. * based on the normal data.
  12351. */
  12352. setupDiffuseColor() {
  12353. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  12354. diffuseColor.assign( vec4( directionToColor( transformedNormalView ), opacityNode ) );
  12355. }
  12356. }
  12357. /** @module EquirectUVNode **/
  12358. /**
  12359. * Can be used to compute texture coordinates for projecting an
  12360. * equirectangular texture onto a mesh for using it as the scene's
  12361. * background.
  12362. *
  12363. * ```js
  12364. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  12365. * ```
  12366. *
  12367. * @augments TempNode
  12368. */
  12369. class EquirectUVNode extends TempNode {
  12370. static get type() {
  12371. return 'EquirectUVNode';
  12372. }
  12373. /**
  12374. * Constructs a new equirect uv node.
  12375. *
  12376. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12377. */
  12378. constructor( dirNode = positionWorldDirection ) {
  12379. super( 'vec2' );
  12380. /**
  12381. * A direction vector for sampling why is by default `positionWorldDirection`.
  12382. *
  12383. * @type {Node<vec3>}
  12384. */
  12385. this.dirNode = dirNode;
  12386. }
  12387. setup() {
  12388. const dir = this.dirNode;
  12389. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  12390. const v = dir.y.clamp( - 1.0, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  12391. return vec2( u, v );
  12392. }
  12393. }
  12394. /**
  12395. * TSL function for creating an equirect uv node.
  12396. *
  12397. * @function
  12398. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  12399. * @returns {EquirectUVNode}
  12400. */
  12401. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode );
  12402. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  12403. /**
  12404. * This class represents a cube render target. It is a special version
  12405. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  12406. *
  12407. * @augments WebGLCubeRenderTarget
  12408. */
  12409. class CubeRenderTarget extends WebGLCubeRenderTarget {
  12410. constructor( size = 1, options = {} ) {
  12411. super( size, options );
  12412. this.isCubeRenderTarget = true;
  12413. }
  12414. /**
  12415. * Converts the given equirectangular texture to a cube map.
  12416. *
  12417. * @param {Renderer} renderer - The renderer.
  12418. * @param {Texture} texture - The equirectangular texture.
  12419. * @return {CubeRenderTarget} A reference to this cube render target.
  12420. */
  12421. fromEquirectangularTexture( renderer, texture$1 ) {
  12422. const currentMinFilter = texture$1.minFilter;
  12423. const currentGenerateMipmaps = texture$1.generateMipmaps;
  12424. texture$1.generateMipmaps = true;
  12425. this.texture.type = texture$1.type;
  12426. this.texture.colorSpace = texture$1.colorSpace;
  12427. this.texture.generateMipmaps = texture$1.generateMipmaps;
  12428. this.texture.minFilter = texture$1.minFilter;
  12429. this.texture.magFilter = texture$1.magFilter;
  12430. const geometry = new BoxGeometry( 5, 5, 5 );
  12431. const uvNode = equirectUV( positionWorldDirection );
  12432. const material = new NodeMaterial();
  12433. material.colorNode = texture( texture$1, uvNode, 0 );
  12434. material.side = BackSide;
  12435. material.blending = NoBlending;
  12436. const mesh = new Mesh( geometry, material );
  12437. const scene = new Scene();
  12438. scene.add( mesh );
  12439. // Avoid blurred poles
  12440. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  12441. const camera = new CubeCamera( 1, 10, this );
  12442. const currentMRT = renderer.getMRT();
  12443. renderer.setMRT( null );
  12444. camera.update( renderer, scene );
  12445. renderer.setMRT( currentMRT );
  12446. texture$1.minFilter = currentMinFilter;
  12447. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  12448. mesh.geometry.dispose();
  12449. mesh.material.dispose();
  12450. return this;
  12451. }
  12452. }
  12453. /** @module CubeMapNode **/
  12454. const _cache$1 = new WeakMap();
  12455. /**
  12456. * This node can be used to automatically convert environment maps in the
  12457. * equirectangular format into the cube map format.
  12458. *
  12459. * @augments TempNode
  12460. */
  12461. class CubeMapNode extends TempNode {
  12462. static get type() {
  12463. return 'CubeMapNode';
  12464. }
  12465. /**
  12466. * Constructs a new cube map node.
  12467. *
  12468. * @param {Node} envNode - The node representing the environment map.
  12469. */
  12470. constructor( envNode ) {
  12471. super( 'vec3' );
  12472. /**
  12473. * The node representing the environment map.
  12474. *
  12475. * @type {Node}
  12476. */
  12477. this.envNode = envNode;
  12478. /**
  12479. * A reference to the internal cube texture.
  12480. *
  12481. * @private
  12482. * @type {CubeTexture}
  12483. * @default null
  12484. */
  12485. this._cubeTexture = null;
  12486. /**
  12487. * A reference to the internal cube texture node.
  12488. *
  12489. * @private
  12490. * @type {CubeTextureNode}
  12491. */
  12492. this._cubeTextureNode = cubeTexture();
  12493. const defaultTexture = new CubeTexture();
  12494. defaultTexture.isRenderTargetTexture = true;
  12495. /**
  12496. * A default cube texture that acts as a placeholder.
  12497. * It is used when the conversion from equirectangular to cube
  12498. * map has not finished yet for a given texture.
  12499. *
  12500. * @private
  12501. * @type {CubeTexture}
  12502. */
  12503. this._defaultTexture = defaultTexture;
  12504. /**
  12505. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  12506. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  12507. *
  12508. * @type {String}
  12509. * @default 'render'
  12510. */
  12511. this.updateBeforeType = NodeUpdateType.RENDER;
  12512. }
  12513. updateBefore( frame ) {
  12514. const { renderer, material } = frame;
  12515. const envNode = this.envNode;
  12516. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  12517. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  12518. if ( texture && texture.isTexture ) {
  12519. const mapping = texture.mapping;
  12520. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  12521. // check for converted cubemap map
  12522. if ( _cache$1.has( texture ) ) {
  12523. const cubeMap = _cache$1.get( texture );
  12524. mapTextureMapping( cubeMap, texture.mapping );
  12525. this._cubeTexture = cubeMap;
  12526. } else {
  12527. // create cube map from equirectangular map
  12528. const image = texture.image;
  12529. if ( isEquirectangularMapReady$1( image ) ) {
  12530. const renderTarget = new CubeRenderTarget( image.height );
  12531. renderTarget.fromEquirectangularTexture( renderer, texture );
  12532. mapTextureMapping( renderTarget.texture, texture.mapping );
  12533. this._cubeTexture = renderTarget.texture;
  12534. _cache$1.set( texture, renderTarget.texture );
  12535. texture.addEventListener( 'dispose', onTextureDispose );
  12536. } else {
  12537. // default cube texture as fallback when equirectangular texture is not yet loaded
  12538. this._cubeTexture = this._defaultTexture;
  12539. }
  12540. }
  12541. //
  12542. this._cubeTextureNode.value = this._cubeTexture;
  12543. } else {
  12544. // envNode already refers to a cube map
  12545. this._cubeTextureNode = this.envNode;
  12546. }
  12547. }
  12548. }
  12549. }
  12550. setup( builder ) {
  12551. this.updateBefore( builder );
  12552. return this._cubeTextureNode;
  12553. }
  12554. }
  12555. /**
  12556. * Returns true if the given equirectangular image has been fully loaded
  12557. * and is ready for further processing.
  12558. *
  12559. * @private
  12560. * @param {Image} image - The equirectangular image to check.
  12561. * @return {Boolean} Whether the image is ready or not.
  12562. */
  12563. function isEquirectangularMapReady$1( image ) {
  12564. if ( image === null || image === undefined ) return false;
  12565. return image.height > 0;
  12566. }
  12567. /**
  12568. * This function is executed when `dispose()` is called on the equirectangular
  12569. * texture. In this case, the generated cube map with its render target
  12570. * is deleted as well.
  12571. *
  12572. * @private
  12573. * @param {Object} event - The event object.
  12574. */
  12575. function onTextureDispose( event ) {
  12576. const texture = event.target;
  12577. texture.removeEventListener( 'dispose', onTextureDispose );
  12578. const renderTarget = _cache$1.get( texture );
  12579. if ( renderTarget !== undefined ) {
  12580. _cache$1.delete( texture );
  12581. renderTarget.dispose();
  12582. }
  12583. }
  12584. /**
  12585. * This function makes sure the generated cube map uses the correct
  12586. * texture mapping that corresponds to the equirectangular original.
  12587. *
  12588. * @private
  12589. * @param {Texture} texture - The cube texture.
  12590. * @param {Number} mapping - The original texture mapping.
  12591. */
  12592. function mapTextureMapping( texture, mapping ) {
  12593. if ( mapping === EquirectangularReflectionMapping ) {
  12594. texture.mapping = CubeReflectionMapping;
  12595. } else if ( mapping === EquirectangularRefractionMapping ) {
  12596. texture.mapping = CubeRefractionMapping;
  12597. }
  12598. }
  12599. /**
  12600. * TSL function for creating a cube map node.
  12601. *
  12602. * @function
  12603. * @param {Node} envNode - The node representing the environment map.
  12604. * @returns {CubeMapNode}
  12605. */
  12606. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode );
  12607. /**
  12608. * Represents a basic model for Image-based lighting (IBL). The environment
  12609. * is defined via environment maps in the equirectangular or cube map format.
  12610. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  12611. * or {@link MeshPhongNodeMaterial}.
  12612. *
  12613. * @augments LightingNode
  12614. */
  12615. class BasicEnvironmentNode extends LightingNode {
  12616. static get type() {
  12617. return 'BasicEnvironmentNode';
  12618. }
  12619. /**
  12620. * Constructs a new basic environment node.
  12621. *
  12622. * @param {Node} [envNode=null] - A node representing the environment.
  12623. */
  12624. constructor( envNode = null ) {
  12625. super();
  12626. /**
  12627. * A node representing the environment.
  12628. *
  12629. * @type {Node}
  12630. * @default null
  12631. */
  12632. this.envNode = envNode;
  12633. }
  12634. setup( builder ) {
  12635. // environment property is used in the finish() method of BasicLightingModel
  12636. builder.context.environment = cubeMapNode( this.envNode );
  12637. }
  12638. }
  12639. /**
  12640. * A specific version of {@link IrradianceNode} that is only relevant
  12641. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  12642. * requires a special scaling factor for the light map.
  12643. *
  12644. * @augments LightingNode
  12645. */
  12646. class BasicLightMapNode extends LightingNode {
  12647. static get type() {
  12648. return 'BasicLightMapNode';
  12649. }
  12650. /**
  12651. * Constructs a new basic light map node.
  12652. *
  12653. * @param {Node<vec3>?} [lightMapNode=null] - The light map node.
  12654. */
  12655. constructor( lightMapNode = null ) {
  12656. super();
  12657. /**
  12658. * The light map node.
  12659. *
  12660. * @type {Node<vec3>?}
  12661. */
  12662. this.lightMapNode = lightMapNode;
  12663. }
  12664. setup( builder ) {
  12665. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  12666. const RECIPROCAL_PI = float( 1 / Math.PI );
  12667. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  12668. }
  12669. }
  12670. /**
  12671. * Abstract class for implementing lighting models. The module defines
  12672. * multiple methods that concrete lighting models can implement. These
  12673. * methods are executed at different points during the light evaluation
  12674. * process.
  12675. */
  12676. class LightingModel {
  12677. /**
  12678. * This method is intended for setting up lighting model and context data
  12679. * which are later used in the evaluation process.
  12680. *
  12681. * @abstract
  12682. * @param {ContextNode} input - The current node context.
  12683. * @param {StackNode} stack - The current stack.
  12684. * @param {NodeBuilder} builder - The current node builder.
  12685. */
  12686. start( /*input, stack, builder*/ ) { }
  12687. /**
  12688. * This method is intended for executing final tasks like final updates
  12689. * to the outgoing light.
  12690. *
  12691. * @abstract
  12692. * @param {ContextNode} input - The current node context.
  12693. * @param {StackNode} stack - The current stack.
  12694. * @param {NodeBuilder} builder - The current node builder.
  12695. */
  12696. finish( /*input, stack, builder*/ ) { }
  12697. /**
  12698. * This method is intended for implementing the direct light term and
  12699. * executed during the build process of directional, point and spot light nodes.
  12700. *
  12701. * @abstract
  12702. * @param {Object} input - The input data.
  12703. * @param {StackNode} stack - The current stack.
  12704. * @param {NodeBuilder} builder - The current node builder.
  12705. */
  12706. direct( /*input, stack, builder*/ ) { }
  12707. /**
  12708. * This method is intended for implementing the direct light term for
  12709. * rect area light nodes.
  12710. *
  12711. * @abstract
  12712. * @param {Object} input - The input data.
  12713. * @param {StackNode} stack - The current stack.
  12714. * @param {NodeBuilder} builder - The current node builder.
  12715. */
  12716. directRectArea( /*input, stack, builder*/ ) {}
  12717. /**
  12718. * This method is intended for implementing the indirect light term.
  12719. *
  12720. * @abstract
  12721. * @param {ContextNode} input - The current node context.
  12722. * @param {StackNode} stack - The current stack.
  12723. * @param {NodeBuilder} builder - The current node builder.
  12724. */
  12725. indirect( /*input, stack, builder*/ ) { }
  12726. /**
  12727. * This method is intended for implementing the ambient occlusion term.
  12728. * Unlike other methods, this method must be called manually by the lighting
  12729. * model in its indirect term.
  12730. *
  12731. * @abstract
  12732. * @param {ContextNode} input - The current node context.
  12733. * @param {StackNode} stack - The current stack.
  12734. * @param {NodeBuilder} builder - The current node builder.
  12735. */
  12736. ambientOcclusion( /*input, stack, builder*/ ) { }
  12737. }
  12738. /**
  12739. * Represents the lighting model for unlit materials. The only light contribution
  12740. * is baked indirect lighting modulated with ambient occlusion and the material's
  12741. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  12742. *
  12743. * @augments LightingModel
  12744. */
  12745. class BasicLightingModel extends LightingModel {
  12746. /**
  12747. * Constructs a new basic lighting model.
  12748. */
  12749. constructor() {
  12750. super();
  12751. }
  12752. /**
  12753. * Implements the baked indirect lighting with its modulation.
  12754. *
  12755. * @param {ContextNode} context - The current node context.
  12756. * @param {StackNode} stack - The current stack.
  12757. * @param {NodeBuilder} builder - The current node builder.
  12758. */
  12759. indirect( context, stack, builder ) {
  12760. const ambientOcclusion = context.ambientOcclusion;
  12761. const reflectedLight = context.reflectedLight;
  12762. const irradianceLightMap = builder.context.irradianceLightMap;
  12763. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  12764. // accumulation (baked indirect lighting only)
  12765. if ( irradianceLightMap ) {
  12766. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  12767. } else {
  12768. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  12769. }
  12770. // modulation
  12771. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12772. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  12773. }
  12774. /**
  12775. * Implements the environment mapping.
  12776. *
  12777. * @param {ContextNode} context - The current node context.
  12778. * @param {StackNode} stack - The current stack.
  12779. * @param {NodeBuilder} builder - The current node builder.
  12780. */
  12781. finish( context, stack, builder ) {
  12782. const material = builder.material;
  12783. const outgoingLight = context.outgoingLight;
  12784. const envNode = builder.context.environment;
  12785. if ( envNode ) {
  12786. switch ( material.combine ) {
  12787. case MultiplyOperation:
  12788. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  12789. break;
  12790. case MixOperation:
  12791. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  12792. break;
  12793. case AddOperation:
  12794. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  12795. break;
  12796. default:
  12797. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  12798. break;
  12799. }
  12800. }
  12801. }
  12802. }
  12803. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  12804. /**
  12805. * Node material version of `MeshBasicMaterial`.
  12806. *
  12807. * @augments NodeMaterial
  12808. */
  12809. class MeshBasicNodeMaterial extends NodeMaterial {
  12810. static get type() {
  12811. return 'MeshBasicNodeMaterial';
  12812. }
  12813. /**
  12814. * Constructs a new mesh basic node material.
  12815. *
  12816. * @param {Object?} parameters - The configuration parameter.
  12817. */
  12818. constructor( parameters ) {
  12819. super();
  12820. /**
  12821. * This flag can be used for type testing.
  12822. *
  12823. * @type {Boolean}
  12824. * @readonly
  12825. * @default true
  12826. */
  12827. this.isMeshBasicNodeMaterial = true;
  12828. /**
  12829. * Although the basic material is by definition unlit, we set
  12830. * this property to `true` since we use a lighting model to compute
  12831. * the outgoing light of the fragment shader.
  12832. *
  12833. * @type {Boolean}
  12834. * @default true
  12835. */
  12836. this.lights = true;
  12837. this.setDefaultValues( _defaultValues$9 );
  12838. this.setValues( parameters );
  12839. }
  12840. /**
  12841. * Basic materials are not affected by normal and bump maps so we
  12842. * return by default {@link module:Normal.normalView}.
  12843. *
  12844. * @return {Node<vec3>} The normal node.
  12845. */
  12846. setupNormal() {
  12847. return normalView; // see #28839
  12848. }
  12849. /**
  12850. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  12851. * to implement the default environment mapping.
  12852. *
  12853. * @param {NodeBuilder} builder - The current node builder.
  12854. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  12855. */
  12856. setupEnvironment( builder ) {
  12857. const envNode = super.setupEnvironment( builder );
  12858. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  12859. }
  12860. /**
  12861. * This method must be overwritten since light maps are evaluated
  12862. * with a special scaling factor for basic materials.
  12863. *
  12864. * @param {NodeBuilder} builder - The current node builder.
  12865. * @return {BasicLightMapNode<vec3>?} The light map node.
  12866. */
  12867. setupLightMap( builder ) {
  12868. let node = null;
  12869. if ( builder.material.lightMap ) {
  12870. node = new BasicLightMapNode( materialLightMap );
  12871. }
  12872. return node;
  12873. }
  12874. /**
  12875. * The material overwrites this method because `lights` is set to `true` but
  12876. * we still want to return the diffuse color as the outgoing light.
  12877. *
  12878. * @return {Node<vec3>} The outgoing light node.
  12879. */
  12880. setupOutgoingLight() {
  12881. return diffuseColor.rgb;
  12882. }
  12883. /**
  12884. * Setups the lighting model.
  12885. *
  12886. * @return {BasicLightingModel} The lighting model.
  12887. */
  12888. setupLightingModel() {
  12889. return new BasicLightingModel();
  12890. }
  12891. }
  12892. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  12893. // Original approximation by Christophe Schlick '94
  12894. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  12895. // Optimized variant (presented by Epic at SIGGRAPH '13)
  12896. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  12897. const fresnel = dotVH.mul( - 5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  12898. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  12899. } ); // validated
  12900. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  12901. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  12902. } ); // validated
  12903. const G_BlinnPhong_Implicit = () => float( 0.25 );
  12904. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  12905. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  12906. } );
  12907. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  12908. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  12909. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  12910. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  12911. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  12912. const G = G_BlinnPhong_Implicit();
  12913. const D = D_BlinnPhong( { dotNH } );
  12914. return F.mul( G ).mul( D );
  12915. } );
  12916. /**
  12917. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  12918. *
  12919. * @augments BasicLightingModel
  12920. */
  12921. class PhongLightingModel extends BasicLightingModel {
  12922. /**
  12923. * Constructs a new phong lighting model.
  12924. *
  12925. * @param {Boolean} [specular=true] - Whether specular is supported or not.
  12926. */
  12927. constructor( specular = true ) {
  12928. super();
  12929. /**
  12930. * Whether specular is supported or not. Set this to `false` if you are
  12931. * looking for a Lambert-like material meaning a material for non-shiny
  12932. * surfaces, without specular highlights.
  12933. *
  12934. * @type {Boolean}
  12935. * @default true
  12936. */
  12937. this.specular = specular;
  12938. }
  12939. /**
  12940. * Implements the direct lighting. The specular portion is optional an can be controlled
  12941. * with the {@link PhongLightingModel#specular} flag.
  12942. *
  12943. * @param {Object} input - The input data.
  12944. * @param {StackNode} stack - The current stack.
  12945. * @param {NodeBuilder} builder - The current node builder.
  12946. */
  12947. direct( { lightDirection, lightColor, reflectedLight } ) {
  12948. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  12949. const irradiance = dotNL.mul( lightColor );
  12950. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  12951. if ( this.specular === true ) {
  12952. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  12953. }
  12954. }
  12955. /**
  12956. * Implements the indirect lighting.
  12957. *
  12958. * @param {ContextNode} input - The current node context.
  12959. * @param {StackNode} stack - The current stack.
  12960. * @param {NodeBuilder} builder - The current node builder.
  12961. */
  12962. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  12963. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  12964. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  12965. }
  12966. }
  12967. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  12968. /**
  12969. * Node material version of `MeshLambertMaterial`.
  12970. *
  12971. * @augments NodeMaterial
  12972. */
  12973. class MeshLambertNodeMaterial extends NodeMaterial {
  12974. static get type() {
  12975. return 'MeshLambertNodeMaterial';
  12976. }
  12977. /**
  12978. * Constructs a new mesh lambert node material.
  12979. *
  12980. * @param {Object?} parameters - The configuration parameter.
  12981. */
  12982. constructor( parameters ) {
  12983. super();
  12984. /**
  12985. * This flag can be used for type testing.
  12986. *
  12987. * @type {Boolean}
  12988. * @readonly
  12989. * @default true
  12990. */
  12991. this.isMeshLambertNodeMaterial = true;
  12992. /**
  12993. * Set to `true` because lambert materials react on lights.
  12994. *
  12995. * @type {Boolean}
  12996. * @default true
  12997. */
  12998. this.lights = true;
  12999. this.setDefaultValues( _defaultValues$8 );
  13000. this.setValues( parameters );
  13001. }
  13002. /**
  13003. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13004. * to implement the default environment mapping.
  13005. *
  13006. * @param {NodeBuilder} builder - The current node builder.
  13007. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13008. */
  13009. setupEnvironment( builder ) {
  13010. const envNode = super.setupEnvironment( builder );
  13011. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13012. }
  13013. /**
  13014. * Setups the lighting model.
  13015. *
  13016. * @return {PhongLightingModel} The lighting model.
  13017. */
  13018. setupLightingModel( /*builder*/ ) {
  13019. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  13020. }
  13021. }
  13022. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  13023. /**
  13024. * Node material version of `MeshPhongMaterial`.
  13025. *
  13026. * @augments NodeMaterial
  13027. */
  13028. class MeshPhongNodeMaterial extends NodeMaterial {
  13029. static get type() {
  13030. return 'MeshPhongNodeMaterial';
  13031. }
  13032. /**
  13033. * Constructs a new mesh lambert node material.
  13034. *
  13035. * @param {Object?} parameters - The configuration parameter.
  13036. */
  13037. constructor( parameters ) {
  13038. super();
  13039. /**
  13040. * This flag can be used for type testing.
  13041. *
  13042. * @type {Boolean}
  13043. * @readonly
  13044. * @default true
  13045. */
  13046. this.isMeshPhongNodeMaterial = true;
  13047. /**
  13048. * Set to `true` because phong materials react on lights.
  13049. *
  13050. * @type {Boolean}
  13051. * @default true
  13052. */
  13053. this.lights = true;
  13054. /**
  13055. * The shininess of phong materials is by default inferred from the `shininess`
  13056. * property. This node property allows to overwrite the default
  13057. * and define the shininess with a node instead.
  13058. *
  13059. * If you don't want to overwrite the shininess but modify the existing
  13060. * value instead, use {@link module:MaterialNode.materialShininess}.
  13061. *
  13062. * @type {Node<float>?}
  13063. * @default null
  13064. */
  13065. this.shininessNode = null;
  13066. /**
  13067. * The specular color of phong materials is by default inferred from the
  13068. * `specular` property. This node property allows to overwrite the default
  13069. * and define the specular color with a node instead.
  13070. *
  13071. * If you don't want to overwrite the specular color but modify the existing
  13072. * value instead, use {@link module:MaterialNode.materialSpecular}.
  13073. *
  13074. * @type {Node<vec3>?}
  13075. * @default null
  13076. */
  13077. this.specularNode = null;
  13078. this.setDefaultValues( _defaultValues$7 );
  13079. this.setValues( parameters );
  13080. }
  13081. /**
  13082. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  13083. * to implement the default environment mapping.
  13084. *
  13085. * @param {NodeBuilder} builder - The current node builder.
  13086. * @return {BasicEnvironmentNode<vec3>?} The environment node.
  13087. */
  13088. setupEnvironment( builder ) {
  13089. const envNode = super.setupEnvironment( builder );
  13090. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  13091. }
  13092. /**
  13093. * Setups the lighting model.
  13094. *
  13095. * @return {PhongLightingModel} The lighting model.
  13096. */
  13097. setupLightingModel( /*builder*/ ) {
  13098. return new PhongLightingModel();
  13099. }
  13100. /**
  13101. * Setups the phong specific node variables.
  13102. *
  13103. * @param {NodeBuilder} builder - The current node builder.
  13104. */
  13105. setupVariants( /*builder*/ ) {
  13106. // SHININESS
  13107. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  13108. shininess.assign( shininessNode );
  13109. // SPECULAR COLOR
  13110. const specularNode = this.specularNode || materialSpecular;
  13111. specularColor.assign( specularNode );
  13112. }
  13113. copy( source ) {
  13114. this.shininessNode = source.shininessNode;
  13115. this.specularNode = source.specularNode;
  13116. return super.copy( source );
  13117. }
  13118. }
  13119. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  13120. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  13121. return float( 0 );
  13122. }
  13123. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  13124. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  13125. return geometryRoughness;
  13126. } );
  13127. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  13128. const { roughness } = inputs;
  13129. const geometryRoughness = getGeometryRoughness();
  13130. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  13131. roughnessFactor = roughnessFactor.add( geometryRoughness );
  13132. roughnessFactor = roughnessFactor.min( 1.0 );
  13133. return roughnessFactor;
  13134. } );
  13135. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  13136. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  13137. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  13138. const a2 = alpha.pow2();
  13139. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  13140. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  13141. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  13142. } ).setLayout( {
  13143. name: 'V_GGX_SmithCorrelated',
  13144. type: 'float',
  13145. inputs: [
  13146. { name: 'alpha', type: 'float' },
  13147. { name: 'dotNL', type: 'float' },
  13148. { name: 'dotNV', type: 'float' }
  13149. ]
  13150. } ); // validated
  13151. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13152. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  13153. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  13154. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  13155. const v = div( 0.5, gv.add( gl ) );
  13156. return v.saturate();
  13157. } ).setLayout( {
  13158. name: 'V_GGX_SmithCorrelated_Anisotropic',
  13159. type: 'float',
  13160. inputs: [
  13161. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13162. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13163. { name: 'dotTV', type: 'float', qualifier: 'in' },
  13164. { name: 'dotBV', type: 'float', qualifier: 'in' },
  13165. { name: 'dotTL', type: 'float', qualifier: 'in' },
  13166. { name: 'dotBL', type: 'float', qualifier: 'in' },
  13167. { name: 'dotNV', type: 'float', qualifier: 'in' },
  13168. { name: 'dotNL', type: 'float', qualifier: 'in' }
  13169. ]
  13170. } );
  13171. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  13172. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  13173. // alpha is "roughness squared" in Disney’s reparameterization
  13174. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  13175. const a2 = alpha.pow2();
  13176. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  13177. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  13178. } ).setLayout( {
  13179. name: 'D_GGX',
  13180. type: 'float',
  13181. inputs: [
  13182. { name: 'alpha', type: 'float' },
  13183. { name: 'dotNH', type: 'float' }
  13184. ]
  13185. } ); // validated
  13186. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  13187. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  13188. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  13189. const a2 = alphaT.mul( alphaB );
  13190. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  13191. const v2 = v.dot( v );
  13192. const w2 = a2.div( v2 );
  13193. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  13194. } ).setLayout( {
  13195. name: 'D_GGX_Anisotropic',
  13196. type: 'float',
  13197. inputs: [
  13198. { name: 'alphaT', type: 'float', qualifier: 'in' },
  13199. { name: 'alphaB', type: 'float', qualifier: 'in' },
  13200. { name: 'dotNH', type: 'float', qualifier: 'in' },
  13201. { name: 'dotTH', type: 'float', qualifier: 'in' },
  13202. { name: 'dotBH', type: 'float', qualifier: 'in' }
  13203. ]
  13204. } );
  13205. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  13206. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  13207. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  13208. const normalView = inputs.normalView || transformedNormalView;
  13209. const alpha = roughness.pow2(); // UE4's roughness
  13210. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13211. const dotNL = normalView.dot( lightDirection ).clamp();
  13212. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13213. const dotNH = normalView.dot( halfDir ).clamp();
  13214. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  13215. let F = F_Schlick( { f0, f90, dotVH } );
  13216. let V, D;
  13217. if ( defined( USE_IRIDESCENCE ) ) {
  13218. F = iridescence.mix( F, f );
  13219. }
  13220. if ( defined( USE_ANISOTROPY ) ) {
  13221. const dotTL = anisotropyT.dot( lightDirection );
  13222. const dotTV = anisotropyT.dot( positionViewDirection );
  13223. const dotTH = anisotropyT.dot( halfDir );
  13224. const dotBL = anisotropyB.dot( lightDirection );
  13225. const dotBV = anisotropyB.dot( positionViewDirection );
  13226. const dotBH = anisotropyB.dot( halfDir );
  13227. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  13228. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  13229. } else {
  13230. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  13231. D = D_GGX( { alpha, dotNH } );
  13232. }
  13233. return F.mul( V ).mul( D );
  13234. } ); // validated
  13235. // Analytical approximation of the DFG LUT, one half of the
  13236. // split-sum approximation used in indirect specular lighting.
  13237. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  13238. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  13239. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  13240. const c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
  13241. const c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
  13242. const r = roughness.mul( c0 ).add( c1 );
  13243. const a004 = r.x.mul( r.x ).min( dotNV.mul( - 9.28 ).exp2() ).mul( r.x ).add( r.y );
  13244. const fab = vec2( - 1.04, 1.04 ).mul( a004 ).add( r.zw );
  13245. return fab;
  13246. } ).setLayout( {
  13247. name: 'DFGApprox',
  13248. type: 'vec2',
  13249. inputs: [
  13250. { name: 'roughness', type: 'float' },
  13251. { name: 'dotNV', type: 'vec3' }
  13252. ]
  13253. } );
  13254. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  13255. const { dotNV, specularColor, specularF90, roughness } = inputs;
  13256. const fab = DFGApprox( { dotNV, roughness } );
  13257. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13258. } );
  13259. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  13260. const x = dotVH.oneMinus().saturate();
  13261. const x2 = x.mul( x );
  13262. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  13263. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  13264. } ).setLayout( {
  13265. name: 'Schlick_to_F0',
  13266. type: 'vec3',
  13267. inputs: [
  13268. { name: 'f', type: 'vec3' },
  13269. { name: 'f90', type: 'float' },
  13270. { name: 'dotVH', type: 'float' }
  13271. ]
  13272. } );
  13273. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13274. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  13275. const alpha = roughness.pow2();
  13276. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  13277. const invAlpha = float( 1.0 ).div( alpha );
  13278. const cos2h = dotNH.pow2();
  13279. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  13280. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  13281. } ).setLayout( {
  13282. name: 'D_Charlie',
  13283. type: 'float',
  13284. inputs: [
  13285. { name: 'roughness', type: 'float' },
  13286. { name: 'dotNH', type: 'float' }
  13287. ]
  13288. } );
  13289. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  13290. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  13291. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  13292. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  13293. } ).setLayout( {
  13294. name: 'V_Neubelt',
  13295. type: 'float',
  13296. inputs: [
  13297. { name: 'dotNV', type: 'float' },
  13298. { name: 'dotNL', type: 'float' }
  13299. ]
  13300. } );
  13301. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  13302. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  13303. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13304. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  13305. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  13306. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  13307. const V = V_Neubelt( { dotNV, dotNL } );
  13308. return sheen.mul( D ).mul( V );
  13309. } );
  13310. // Rect Area Light
  13311. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  13312. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  13313. // code: https://github.com/selfshadow/ltc_code/
  13314. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  13315. const LUT_SIZE = 64.0;
  13316. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  13317. const LUT_BIAS = 0.5 / LUT_SIZE;
  13318. const dotNV = N.dot( V ).saturate();
  13319. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  13320. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  13321. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  13322. return uv;
  13323. } ).setLayout( {
  13324. name: 'LTC_Uv',
  13325. type: 'vec2',
  13326. inputs: [
  13327. { name: 'N', type: 'vec3' },
  13328. { name: 'V', type: 'vec3' },
  13329. { name: 'roughness', type: 'float' }
  13330. ]
  13331. } );
  13332. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  13333. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  13334. // An approximation of the form factor of a horizon-clipped rectangle.
  13335. const l = f.length();
  13336. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  13337. } ).setLayout( {
  13338. name: 'LTC_ClippedSphereFormFactor',
  13339. type: 'float',
  13340. inputs: [
  13341. { name: 'f', type: 'vec3' }
  13342. ]
  13343. } );
  13344. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  13345. const x = v1.dot( v2 );
  13346. const y = x.abs().toVar();
  13347. // rational polynomial approximation to theta / sin( theta ) / 2PI
  13348. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  13349. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  13350. const v = a.div( b );
  13351. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  13352. return v1.cross( v2 ).mul( theta_sintheta );
  13353. } ).setLayout( {
  13354. name: 'LTC_EdgeVectorFormFactor',
  13355. type: 'vec3',
  13356. inputs: [
  13357. { name: 'v1', type: 'vec3' },
  13358. { name: 'v2', type: 'vec3' }
  13359. ]
  13360. } );
  13361. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  13362. // bail if point is on back side of plane of light
  13363. // assumes ccw winding order of light vertices
  13364. const v1 = p1.sub( p0 ).toVar();
  13365. const v2 = p3.sub( p0 ).toVar();
  13366. const lightNormal = v1.cross( v2 );
  13367. const result = vec3().toVar();
  13368. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  13369. // construct orthonormal basis around N
  13370. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  13371. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  13372. // compute transform
  13373. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  13374. // transform rect
  13375. // & project rect onto sphere
  13376. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  13377. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  13378. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  13379. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  13380. // calculate vector form factor
  13381. const vectorFormFactor = vec3( 0 ).toVar();
  13382. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  13383. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  13384. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  13385. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  13386. // adjust for horizon clipping
  13387. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  13388. } );
  13389. return result;
  13390. } ).setLayout( {
  13391. name: 'LTC_Evaluate',
  13392. type: 'vec3',
  13393. inputs: [
  13394. { name: 'N', type: 'vec3' },
  13395. { name: 'V', type: 'vec3' },
  13396. { name: 'P', type: 'vec3' },
  13397. { name: 'mInv', type: 'mat3' },
  13398. { name: 'p0', type: 'vec3' },
  13399. { name: 'p1', type: 'vec3' },
  13400. { name: 'p2', type: 'vec3' },
  13401. { name: 'p3', type: 'vec3' }
  13402. ]
  13403. } );
  13404. /** @module TextureBicubic **/
  13405. // Mipped Bicubic Texture Filtering by N8
  13406. // https://www.shadertoy.com/view/Dl2SDW
  13407. const bC = 1.0 / 6.0;
  13408. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  13409. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  13410. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( - 3.0, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  13411. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  13412. const g0 = ( a ) => w0( a ).add( w1( a ) );
  13413. const g1 = ( a ) => w2( a ).add( w3( a ) );
  13414. // h0 and h1 are the two offset functions
  13415. const h0 = ( a ) => add( - 1.0, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  13416. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  13417. const bicubic = ( textureNode, texelSize, lod ) => {
  13418. const uv = textureNode.uvNode;
  13419. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  13420. const iuv = floor( uvScaled );
  13421. const fuv = fract( uvScaled );
  13422. const g0x = g0( fuv.x );
  13423. const g1x = g1( fuv.x );
  13424. const h0x = h0( fuv.x );
  13425. const h1x = h1( fuv.x );
  13426. const h0y = h0( fuv.y );
  13427. const h1y = h1( fuv.y );
  13428. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13429. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  13430. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13431. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  13432. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  13433. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  13434. return a.add( b );
  13435. };
  13436. /**
  13437. * Applies mipped bicubic texture filtering to the given texture node.
  13438. *
  13439. * @method
  13440. * @param {TextureNode} textureNode - The texture node that should be filtered.
  13441. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  13442. * @return {Node} The filtered texture sample.
  13443. */
  13444. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  13445. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  13446. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  13447. const fLodSizeInv = div( 1.0, fLodSize );
  13448. const cLodSizeInv = div( 1.0, cLodSize );
  13449. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  13450. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  13451. return fract( lodNode ).mix( fSample, cSample );
  13452. } );
  13453. //
  13454. // Transmission
  13455. //
  13456. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  13457. // Direction of refracted light.
  13458. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  13459. // Compute rotation-independent scaling of the model matrix.
  13460. const modelScale = vec3(
  13461. length( modelMatrix[ 0 ].xyz ),
  13462. length( modelMatrix[ 1 ].xyz ),
  13463. length( modelMatrix[ 2 ].xyz )
  13464. );
  13465. // The thickness is specified in local space.
  13466. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  13467. } ).setLayout( {
  13468. name: 'getVolumeTransmissionRay',
  13469. type: 'vec3',
  13470. inputs: [
  13471. { name: 'n', type: 'vec3' },
  13472. { name: 'v', type: 'vec3' },
  13473. { name: 'thickness', type: 'float' },
  13474. { name: 'ior', type: 'float' },
  13475. { name: 'modelMatrix', type: 'mat4' }
  13476. ]
  13477. } );
  13478. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  13479. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  13480. // an IOR of 1.5 results in the default amount of microfacet refraction.
  13481. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  13482. } ).setLayout( {
  13483. name: 'applyIorToRoughness',
  13484. type: 'float',
  13485. inputs: [
  13486. { name: 'roughness', type: 'float' },
  13487. { name: 'ior', type: 'float' }
  13488. ]
  13489. } );
  13490. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  13491. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  13492. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  13493. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  13494. const transmissionSample = vTexture.sample( fragCoord );
  13495. //const transmissionSample = viewportMipTexture( fragCoord );
  13496. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  13497. return textureBicubic( transmissionSample, lod );
  13498. } );
  13499. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  13500. If( attenuationDistance.notEqual( 0 ), () => {
  13501. // Compute light attenuation using Beer's law.
  13502. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  13503. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  13504. return transmittance;
  13505. } );
  13506. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  13507. return vec3( 1.0 );
  13508. } ).setLayout( {
  13509. name: 'volumeAttenuation',
  13510. type: 'vec3',
  13511. inputs: [
  13512. { name: 'transmissionDistance', type: 'float' },
  13513. { name: 'attenuationColor', type: 'vec3' },
  13514. { name: 'attenuationDistance', type: 'float' }
  13515. ]
  13516. } );
  13517. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  13518. let transmittedLight, transmittance;
  13519. if ( dispersion ) {
  13520. transmittedLight = vec4().toVar();
  13521. transmittance = vec3().toVar();
  13522. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  13523. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  13524. Loop( { start: 0, end: 3 }, ( { i } ) => {
  13525. const ior = iors.element( i );
  13526. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13527. const refractedRayExit = position.add( transmissionRay );
  13528. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13529. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13530. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13531. refractionCoords.addAssign( 1.0 );
  13532. refractionCoords.divAssign( 2.0 );
  13533. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13534. // Sample framebuffer to get pixel the refracted ray hits.
  13535. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  13536. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  13537. transmittedLight.a.addAssign( transmissionSample.a );
  13538. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  13539. } );
  13540. transmittedLight.a.divAssign( 3.0 );
  13541. } else {
  13542. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  13543. const refractedRayExit = position.add( transmissionRay );
  13544. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  13545. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  13546. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  13547. refractionCoords.addAssign( 1.0 );
  13548. refractionCoords.divAssign( 2.0 );
  13549. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  13550. // Sample framebuffer to get pixel the refracted ray hits.
  13551. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  13552. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  13553. }
  13554. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  13555. const dotNV = n.dot( v ).clamp();
  13556. // Get the specular component.
  13557. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  13558. dotNV,
  13559. specularColor,
  13560. specularF90,
  13561. roughness
  13562. } ) );
  13563. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  13564. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  13565. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  13566. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  13567. } );
  13568. //
  13569. // Iridescence
  13570. //
  13571. // XYZ to linear-sRGB color space
  13572. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  13573. 3.2404542, - 0.9692660, 0.0556434,
  13574. - 1.5371385, 1.8760108, - 0.2040259,
  13575. - 0.4985314, 0.0415560, 1.0572252
  13576. );
  13577. // Assume air interface for top
  13578. // Note: We don't handle the case fresnel0 == 1
  13579. const Fresnel0ToIor = ( fresnel0 ) => {
  13580. const sqrtF0 = fresnel0.sqrt();
  13581. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  13582. };
  13583. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  13584. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  13585. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  13586. };
  13587. // Fresnel equations for dielectric/dielectric interfaces.
  13588. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  13589. // Evaluation XYZ sensitivity curves in Fourier space
  13590. const evalSensitivity = ( OPD, shift ) => {
  13591. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  13592. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  13593. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  13594. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  13595. const x = float( 9.7470e-14 * Math.sqrt( 2.0 * Math.PI * 4.5282e+09 ) ).mul( phase.mul( 2.2399e+06 ).add( shift.x ).cos() ).mul( phase.pow2().mul( - 4.5282e+09 ).exp() );
  13596. let xyz = val.mul( VAR.mul( 2.0 * Math.PI ).sqrt() ).mul( pos.mul( phase ).add( shift ).cos() ).mul( phase.pow2().negate().mul( VAR ).exp() );
  13597. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  13598. const rgb = XYZ_TO_REC709.mul( xyz );
  13599. return rgb;
  13600. };
  13601. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  13602. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  13603. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  13604. // Evaluate the cosTheta on the base layer (Snell law)
  13605. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  13606. // Handle TIR:
  13607. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  13608. If( cosTheta2Sq.lessThan( 0 ), () => {
  13609. return vec3( 1.0 );
  13610. } );
  13611. const cosTheta2 = cosTheta2Sq.sqrt();
  13612. // First interface
  13613. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  13614. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  13615. //const R21 = R12;
  13616. const T121 = R12.oneMinus();
  13617. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  13618. const phi21 = float( Math.PI ).sub( phi12 );
  13619. // Second interface
  13620. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  13621. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  13622. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  13623. const phi23 = vec3(
  13624. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13625. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  13626. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  13627. );
  13628. // Phase shift
  13629. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  13630. const phi = vec3( phi21 ).add( phi23 );
  13631. // Compound terms
  13632. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  13633. const r123 = R123.sqrt();
  13634. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  13635. // Reflectance term for m = 0 (DC term amplitude)
  13636. const C0 = R12.add( Rs );
  13637. const I = C0.toVar();
  13638. // Reflectance term for m > 0 (pairs of diracs)
  13639. const Cm = Rs.sub( T121 ).toVar();
  13640. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  13641. Cm.mulAssign( r123 );
  13642. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  13643. I.addAssign( Cm.mul( Sm ) );
  13644. } );
  13645. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  13646. return I.max( vec3( 0.0 ) );
  13647. } ).setLayout( {
  13648. name: 'evalIridescence',
  13649. type: 'vec3',
  13650. inputs: [
  13651. { name: 'outsideIOR', type: 'float' },
  13652. { name: 'eta2', type: 'float' },
  13653. { name: 'cosTheta1', type: 'float' },
  13654. { name: 'thinFilmThickness', type: 'float' },
  13655. { name: 'baseF0', type: 'vec3' }
  13656. ]
  13657. } );
  13658. //
  13659. // Sheen
  13660. //
  13661. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  13662. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  13663. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  13664. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  13665. const dotNV = normal.dot( viewDir ).saturate();
  13666. const r2 = roughness.pow2();
  13667. const a = select(
  13668. roughness.lessThan( 0.25 ),
  13669. float( - 339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  13670. float( - 8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  13671. );
  13672. const b = select(
  13673. roughness.lessThan( 0.25 ),
  13674. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  13675. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  13676. );
  13677. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  13678. return DG.mul( 1.0 / Math.PI ).saturate();
  13679. } );
  13680. const clearcoatF0 = vec3( 0.04 );
  13681. const clearcoatF90 = float( 1 );
  13682. /**
  13683. * Represents the lighting model for a PBR material.
  13684. *
  13685. * @augments LightingModel
  13686. */
  13687. class PhysicalLightingModel extends LightingModel {
  13688. /**
  13689. * Constructs a new physical lighting model.
  13690. *
  13691. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  13692. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  13693. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  13694. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  13695. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  13696. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  13697. */
  13698. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  13699. super();
  13700. /**
  13701. * Whether clearcoat is supported or not.
  13702. *
  13703. * @type {Boolean}
  13704. * @default false
  13705. */
  13706. this.clearcoat = clearcoat;
  13707. /**
  13708. * Whether sheen is supported or not.
  13709. *
  13710. * @type {Boolean}
  13711. * @default false
  13712. */
  13713. this.sheen = sheen;
  13714. /**
  13715. * Whether iridescence is supported or not.
  13716. *
  13717. * @type {Boolean}
  13718. * @default false
  13719. */
  13720. this.iridescence = iridescence;
  13721. /**
  13722. * Whether anisotropy is supported or not.
  13723. *
  13724. * @type {Boolean}
  13725. * @default false
  13726. */
  13727. this.anisotropy = anisotropy;
  13728. /**
  13729. * Whether transmission is supported or not.
  13730. *
  13731. * @type {Boolean}
  13732. * @default false
  13733. */
  13734. this.transmission = transmission;
  13735. /**
  13736. * Whether dispersion is supported or not.
  13737. *
  13738. * @type {Boolean}
  13739. * @default false
  13740. */
  13741. this.dispersion = dispersion;
  13742. /**
  13743. * The clear coat radiance.
  13744. *
  13745. * @type {Node?}
  13746. * @default null
  13747. */
  13748. this.clearcoatRadiance = null;
  13749. /**
  13750. * The clear coat specular direct.
  13751. *
  13752. * @type {Node?}
  13753. * @default null
  13754. */
  13755. this.clearcoatSpecularDirect = null;
  13756. /**
  13757. * The clear coat specular indirect.
  13758. *
  13759. * @type {Node?}
  13760. * @default null
  13761. */
  13762. this.clearcoatSpecularIndirect = null;
  13763. /**
  13764. * The sheen specular direct.
  13765. *
  13766. * @type {Node?}
  13767. * @default null
  13768. */
  13769. this.sheenSpecularDirect = null;
  13770. /**
  13771. * The sheen specular indirect.
  13772. *
  13773. * @type {Node?}
  13774. * @default null
  13775. */
  13776. this.sheenSpecularIndirect = null;
  13777. /**
  13778. * The iridescence Fresnel.
  13779. *
  13780. * @type {Node?}
  13781. * @default null
  13782. */
  13783. this.iridescenceFresnel = null;
  13784. /**
  13785. * The iridescence F0.
  13786. *
  13787. * @type {Node?}
  13788. * @default null
  13789. */
  13790. this.iridescenceF0 = null;
  13791. }
  13792. /**
  13793. * Depending on what features are requested, the method prepares certain node variables
  13794. * which are later used for lighting computations.
  13795. *
  13796. * @param {ContextNode} context - The current node context.
  13797. */
  13798. start( context ) {
  13799. if ( this.clearcoat === true ) {
  13800. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  13801. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  13802. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  13803. }
  13804. if ( this.sheen === true ) {
  13805. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  13806. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  13807. }
  13808. if ( this.iridescence === true ) {
  13809. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  13810. this.iridescenceFresnel = evalIridescence( {
  13811. outsideIOR: float( 1.0 ),
  13812. eta2: iridescenceIOR,
  13813. cosTheta1: dotNVi,
  13814. thinFilmThickness: iridescenceThickness,
  13815. baseF0: specularColor
  13816. } );
  13817. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  13818. }
  13819. if ( this.transmission === true ) {
  13820. const position = positionWorld;
  13821. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  13822. const n = transformedNormalWorld;
  13823. context.backdrop = getIBLVolumeRefraction(
  13824. n,
  13825. v,
  13826. roughness,
  13827. diffuseColor,
  13828. specularColor,
  13829. specularF90, // specularF90
  13830. position, // positionWorld
  13831. modelWorldMatrix, // modelMatrix
  13832. cameraViewMatrix, // viewMatrix
  13833. cameraProjectionMatrix, // projMatrix
  13834. ior,
  13835. thickness,
  13836. attenuationColor,
  13837. attenuationDistance,
  13838. this.dispersion ? dispersion : null
  13839. );
  13840. context.backdropAlpha = transmission;
  13841. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  13842. }
  13843. }
  13844. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  13845. // Approximates multi-scattering in order to preserve energy.
  13846. // http://www.jcgt.org/published/0008/01/03/
  13847. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  13848. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13849. const fab = DFGApprox( { roughness, dotNV } );
  13850. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  13851. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  13852. const Ess = fab.x.add( fab.y );
  13853. const Ems = Ess.oneMinus();
  13854. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  13855. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  13856. singleScatter.addAssign( FssEss );
  13857. multiScatter.addAssign( Fms.mul( Ems ) );
  13858. }
  13859. /**
  13860. * Implements the direct light.
  13861. *
  13862. * @param {Object} input - The input data.
  13863. * @param {StackNode} stack - The current stack.
  13864. * @param {NodeBuilder} builder - The current node builder.
  13865. */
  13866. direct( { lightDirection, lightColor, reflectedLight } ) {
  13867. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  13868. const irradiance = dotNL.mul( lightColor );
  13869. if ( this.sheen === true ) {
  13870. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  13871. }
  13872. if ( this.clearcoat === true ) {
  13873. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  13874. const ccIrradiance = dotNLcc.mul( lightColor );
  13875. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  13876. }
  13877. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  13878. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_GGX( { lightDirection, f0: specularColor, f90: 1, roughness, iridescence: this.iridescence, f: this.iridescenceFresnel, USE_IRIDESCENCE: this.iridescence, USE_ANISOTROPY: this.anisotropy } ) ) );
  13879. }
  13880. /**
  13881. * This method is intended for implementing the direct light term for
  13882. * rect area light nodes.
  13883. *
  13884. * @param {Object} input - The input data.
  13885. * @param {StackNode} stack - The current stack.
  13886. * @param {NodeBuilder} builder - The current node builder.
  13887. */
  13888. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  13889. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  13890. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  13891. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  13892. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  13893. const N = transformedNormalView;
  13894. const V = positionViewDirection;
  13895. const P = positionView.toVar();
  13896. const uv = LTC_Uv( { N, V, roughness } );
  13897. const t1 = ltc_1.sample( uv ).toVar();
  13898. const t2 = ltc_2.sample( uv ).toVar();
  13899. const mInv = mat3(
  13900. vec3( t1.x, 0, t1.y ),
  13901. vec3( 0, 1, 0 ),
  13902. vec3( t1.z, 0, t1.w )
  13903. ).toVar();
  13904. // LTC Fresnel Approximation by Stephen Hill
  13905. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  13906. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  13907. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  13908. reflectedLight.directDiffuse.addAssign( lightColor.mul( diffuseColor ).mul( LTC_Evaluate( { N, V, P, mInv: mat3( 1, 0, 0, 0, 1, 0, 0, 0, 1 ), p0, p1, p2, p3 } ) ) );
  13909. }
  13910. /**
  13911. * Implements the indirect lighting.
  13912. *
  13913. * @param {ContextNode} context - The current node context.
  13914. * @param {StackNode} stack - The current stack.
  13915. * @param {NodeBuilder} builder - The current node builder.
  13916. */
  13917. indirect( context, stack, builder ) {
  13918. this.indirectDiffuse( context, stack, builder );
  13919. this.indirectSpecular( context, stack, builder );
  13920. this.ambientOcclusion( context, stack, builder );
  13921. }
  13922. /**
  13923. * Implements the indirect diffuse term.
  13924. *
  13925. * @param {ContextNode} input - The current node context.
  13926. * @param {StackNode} stack - The current stack.
  13927. * @param {NodeBuilder} builder - The current node builder.
  13928. */
  13929. indirectDiffuse( { irradiance, reflectedLight } ) {
  13930. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  13931. }
  13932. /**
  13933. * Implements the indirect specular term.
  13934. *
  13935. * @param {ContextNode} input - The current node context.
  13936. * @param {StackNode} stack - The current stack.
  13937. * @param {NodeBuilder} builder - The current node builder.
  13938. */
  13939. indirectSpecular( { radiance, iblIrradiance, reflectedLight } ) {
  13940. if ( this.sheen === true ) {
  13941. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  13942. sheen,
  13943. IBLSheenBRDF( {
  13944. normal: transformedNormalView,
  13945. viewDir: positionViewDirection,
  13946. roughness: sheenRoughness
  13947. } )
  13948. ) );
  13949. }
  13950. if ( this.clearcoat === true ) {
  13951. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  13952. const clearcoatEnv = EnvironmentBRDF( {
  13953. dotNV: dotNVcc,
  13954. specularColor: clearcoatF0,
  13955. specularF90: clearcoatF90,
  13956. roughness: clearcoatRoughness
  13957. } );
  13958. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  13959. }
  13960. // Both indirect specular and indirect diffuse light accumulate here
  13961. const singleScattering = vec3().toVar( 'singleScattering' );
  13962. const multiScattering = vec3().toVar( 'multiScattering' );
  13963. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  13964. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  13965. const totalScattering = singleScattering.add( multiScattering );
  13966. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  13967. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  13968. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  13969. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  13970. }
  13971. /**
  13972. * Implements the ambient occlusion term.
  13973. *
  13974. * @param {ContextNode} input - The current node context.
  13975. * @param {StackNode} stack - The current stack.
  13976. * @param {NodeBuilder} builder - The current node builder.
  13977. */
  13978. ambientOcclusion( { ambientOcclusion, reflectedLight } ) {
  13979. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  13980. const aoNV = dotNV.add( ambientOcclusion );
  13981. const aoExp = roughness.mul( - 16.0 ).oneMinus().negate().exp2();
  13982. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  13983. if ( this.clearcoat === true ) {
  13984. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  13985. }
  13986. if ( this.sheen === true ) {
  13987. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  13988. }
  13989. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  13990. reflectedLight.indirectSpecular.mulAssign( aoNode );
  13991. }
  13992. /**
  13993. * Used for final lighting accumulations depending on the requested features.
  13994. *
  13995. * @param {ContextNode} context - The current node context.
  13996. * @param {StackNode} stack - The current stack.
  13997. * @param {NodeBuilder} builder - The current node builder.
  13998. */
  13999. finish( context ) {
  14000. const { outgoingLight } = context;
  14001. if ( this.clearcoat === true ) {
  14002. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  14003. const Fcc = F_Schlick( {
  14004. dotVH: dotNVcc,
  14005. f0: clearcoatF0,
  14006. f90: clearcoatF90
  14007. } );
  14008. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  14009. outgoingLight.assign( clearcoatLight );
  14010. }
  14011. if ( this.sheen === true ) {
  14012. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  14013. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  14014. outgoingLight.assign( sheenLight );
  14015. }
  14016. }
  14017. }
  14018. // These defines must match with PMREMGenerator
  14019. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  14020. const cubeUV_m0 = /*@__PURE__*/ float( - 2.0 );
  14021. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  14022. const cubeUV_m1 = /*@__PURE__*/ float( - 1.0 );
  14023. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  14024. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  14025. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  14026. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  14027. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  14028. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  14029. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  14030. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  14031. // These shader functions convert between the UV coordinates of a single face of
  14032. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  14033. // sampling a textureCube (not generally normalized ).
  14034. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  14035. const absDirection = vec3( abs( direction ) ).toVar();
  14036. const face = float( - 1.0 ).toVar();
  14037. If( absDirection.x.greaterThan( absDirection.z ), () => {
  14038. If( absDirection.x.greaterThan( absDirection.y ), () => {
  14039. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  14040. } ).Else( () => {
  14041. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14042. } );
  14043. } ).Else( () => {
  14044. If( absDirection.z.greaterThan( absDirection.y ), () => {
  14045. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  14046. } ).Else( () => {
  14047. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  14048. } );
  14049. } );
  14050. return face;
  14051. } ).setLayout( {
  14052. name: 'getFace',
  14053. type: 'float',
  14054. inputs: [
  14055. { name: 'direction', type: 'vec3' }
  14056. ]
  14057. } );
  14058. // RH coordinate system; PMREM face-indexing convention
  14059. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  14060. const uv = vec2().toVar();
  14061. If( face.equal( 0.0 ), () => {
  14062. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  14063. } ).ElseIf( face.equal( 1.0 ), () => {
  14064. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  14065. } ).ElseIf( face.equal( 2.0 ), () => {
  14066. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  14067. } ).ElseIf( face.equal( 3.0 ), () => {
  14068. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  14069. } ).ElseIf( face.equal( 4.0 ), () => {
  14070. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  14071. } ).Else( () => {
  14072. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  14073. } );
  14074. return mul( 0.5, uv.add( 1.0 ) );
  14075. } ).setLayout( {
  14076. name: 'getUV',
  14077. type: 'vec2',
  14078. inputs: [
  14079. { name: 'direction', type: 'vec3' },
  14080. { name: 'face', type: 'float' }
  14081. ]
  14082. } );
  14083. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  14084. const mip = float( 0.0 ).toVar();
  14085. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  14086. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  14087. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  14088. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  14089. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  14090. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  14091. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  14092. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  14093. } ).Else( () => {
  14094. mip.assign( float( - 2.0 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  14095. } );
  14096. return mip;
  14097. } ).setLayout( {
  14098. name: 'roughnessToMip',
  14099. type: 'float',
  14100. inputs: [
  14101. { name: 'roughness', type: 'float' }
  14102. ]
  14103. } );
  14104. // RH coordinate system; PMREM face-indexing convention
  14105. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  14106. const uv = uv_immutable.toVar();
  14107. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  14108. const direction = vec3( uv, 1.0 ).toVar();
  14109. If( face.equal( 0.0 ), () => {
  14110. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  14111. } ).ElseIf( face.equal( 1.0 ), () => {
  14112. direction.assign( direction.xzy );
  14113. direction.xz.mulAssign( - 1.0 ); // ( -u, 1, -v ) pos y
  14114. } ).ElseIf( face.equal( 2.0 ), () => {
  14115. direction.x.mulAssign( - 1.0 ); // ( -u, v, 1 ) pos z
  14116. } ).ElseIf( face.equal( 3.0 ), () => {
  14117. direction.assign( direction.zyx );
  14118. direction.xz.mulAssign( - 1.0 ); // ( -1, v, -u ) neg x
  14119. } ).ElseIf( face.equal( 4.0 ), () => {
  14120. direction.assign( direction.xzy );
  14121. direction.xy.mulAssign( - 1.0 ); // ( -u, -1, v ) neg y
  14122. } ).ElseIf( face.equal( 5.0 ), () => {
  14123. direction.z.mulAssign( - 1.0 ); // ( u, v, -1 ) neg zS
  14124. } );
  14125. return direction;
  14126. } ).setLayout( {
  14127. name: 'getDirection',
  14128. type: 'vec3',
  14129. inputs: [
  14130. { name: 'uv', type: 'vec2' },
  14131. { name: 'face', type: 'float' }
  14132. ]
  14133. } );
  14134. //
  14135. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14136. const roughness = float( roughness_immutable );
  14137. const sampleDir = vec3( sampleDir_immutable );
  14138. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  14139. const mipF = fract( mip );
  14140. const mipInt = floor( mip );
  14141. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14142. If( mipF.notEqual( 0.0 ), () => {
  14143. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  14144. color0.assign( mix( color0, color1, mipF ) );
  14145. } );
  14146. return color0;
  14147. } );
  14148. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  14149. const mipInt = float( mipInt_immutable ).toVar();
  14150. const direction = vec3( direction_immutable );
  14151. const face = float( getFace( direction ) ).toVar();
  14152. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  14153. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  14154. const faceSize = float( exp2( mipInt ) ).toVar();
  14155. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  14156. If( face.greaterThan( 2.0 ), () => {
  14157. uv.y.addAssign( faceSize );
  14158. face.subAssign( 3.0 );
  14159. } );
  14160. uv.x.addAssign( face.mul( faceSize ) );
  14161. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  14162. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  14163. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  14164. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  14165. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  14166. } );
  14167. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14168. const cosTheta = cos( theta );
  14169. // Rodrigues' axis-angle rotation
  14170. const sampleDirection = outputDirection.mul( cosTheta )
  14171. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  14172. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  14173. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  14174. } );
  14175. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  14176. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  14177. If( all( axis.equals( vec3( 0.0 ) ) ), () => {
  14178. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  14179. } );
  14180. axis.assign( normalize( axis ) );
  14181. const gl_FragColor = vec3().toVar();
  14182. gl_FragColor.addAssign( weights.element( int( 0 ) ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14183. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  14184. If( i.greaterThanEqual( samples ), () => {
  14185. Break();
  14186. } );
  14187. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  14188. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta: theta.mul( - 1.0 ), axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14189. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  14190. } );
  14191. return vec4( gl_FragColor, 1 );
  14192. } );
  14193. /** @module PMREMNode **/
  14194. let _generator = null;
  14195. const _cache = new WeakMap();
  14196. /**
  14197. * Generates the cubeUV size based on the given image height.
  14198. *
  14199. * @private
  14200. * @param {Number} imageHeight - The image height.
  14201. * @return {{texelWidth: Number,texelHeight: Number, maxMip: Number}} The result object.
  14202. */
  14203. function _generateCubeUVSize( imageHeight ) {
  14204. const maxMip = Math.log2( imageHeight ) - 2;
  14205. const texelHeight = 1.0 / imageHeight;
  14206. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  14207. return { texelWidth, texelHeight, maxMip };
  14208. }
  14209. /**
  14210. * Generates a PMREM from the given texture .
  14211. *
  14212. * @private
  14213. * @param {Texture} texture - The texture to create the PMREM for.
  14214. * @return {Texture} The PMREM.
  14215. */
  14216. function _getPMREMFromTexture( texture ) {
  14217. let cacheTexture = _cache.get( texture );
  14218. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : - 1;
  14219. if ( pmremVersion !== texture.pmremVersion ) {
  14220. const image = texture.image;
  14221. if ( texture.isCubeTexture ) {
  14222. if ( isCubeMapReady( image ) ) {
  14223. cacheTexture = _generator.fromCubemap( texture, cacheTexture );
  14224. } else {
  14225. return null;
  14226. }
  14227. } else {
  14228. if ( isEquirectangularMapReady( image ) ) {
  14229. cacheTexture = _generator.fromEquirectangular( texture, cacheTexture );
  14230. } else {
  14231. return null;
  14232. }
  14233. }
  14234. cacheTexture.pmremVersion = texture.pmremVersion;
  14235. _cache.set( texture, cacheTexture );
  14236. }
  14237. return cacheTexture.texture;
  14238. }
  14239. /**
  14240. * This node represents a PMREM which is a special type of preprocessed
  14241. * environment map intended for PBR materials.
  14242. *
  14243. * ```js
  14244. * const material = new MeshStandardNodeMaterial();
  14245. * material.envNode = pmremTexture( envMap );
  14246. * ```
  14247. *
  14248. * @augments TempNode
  14249. */
  14250. class PMREMNode extends TempNode {
  14251. static get type() {
  14252. return 'PMREMNode';
  14253. }
  14254. /**
  14255. * Constructs a new function overloading node.
  14256. *
  14257. * @param {Texture} value - The input texture.
  14258. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14259. * @param {Node<float>} [levelNode=null] - The level node.
  14260. */
  14261. constructor( value, uvNode = null, levelNode = null ) {
  14262. super( 'vec3' );
  14263. /**
  14264. * Reference to the input texture.
  14265. *
  14266. * @private
  14267. * @type {Texture}
  14268. */
  14269. this._value = value;
  14270. /**
  14271. * Reference to the generated PMREM.
  14272. *
  14273. * @private
  14274. * @type {Texture | null}
  14275. * @default null
  14276. */
  14277. this._pmrem = null;
  14278. /**
  14279. * The uv node.
  14280. *
  14281. * @type {Node<vec2>}
  14282. */
  14283. this.uvNode = uvNode;
  14284. /**
  14285. * The level node.
  14286. *
  14287. * @type {Node<float>}
  14288. */
  14289. this.levelNode = levelNode;
  14290. /**
  14291. * Reference to a PMREM generator.
  14292. *
  14293. * @private
  14294. * @type {PMREMGenerator}
  14295. * @default null
  14296. */
  14297. this._generator = null;
  14298. const defaultTexture = new Texture();
  14299. defaultTexture.isRenderTargetTexture = true;
  14300. /**
  14301. * The texture node holding the generated PMREM.
  14302. *
  14303. * @private
  14304. * @type {TextureNode}
  14305. */
  14306. this._texture = texture( defaultTexture );
  14307. /**
  14308. * A uniform representing the PMREM's width.
  14309. *
  14310. * @private
  14311. * @type {UniformNode<float>}
  14312. */
  14313. this._width = uniform( 0 );
  14314. /**
  14315. * A uniform representing the PMREM's height.
  14316. *
  14317. * @private
  14318. * @type {UniformNode<float>}
  14319. */
  14320. this._height = uniform( 0 );
  14321. /**
  14322. * A uniform representing the PMREM's max Mip.
  14323. *
  14324. * @private
  14325. * @type {UniformNode<float>}
  14326. */
  14327. this._maxMip = uniform( 0 );
  14328. /**
  14329. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  14330. *
  14331. * @type {String}
  14332. * @default 'render'
  14333. */
  14334. this.updateBeforeType = NodeUpdateType.RENDER;
  14335. }
  14336. set value( value ) {
  14337. this._value = value;
  14338. this._pmrem = null;
  14339. }
  14340. /**
  14341. * The node's texture value.
  14342. *
  14343. * @type {Texture}
  14344. */
  14345. get value() {
  14346. return this._value;
  14347. }
  14348. /**
  14349. * Uses the given PMREM texture to update internal values.
  14350. *
  14351. * @param {Texture} texture - The PMREM texture.
  14352. */
  14353. updateFromTexture( texture ) {
  14354. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  14355. this._texture.value = texture;
  14356. this._width.value = cubeUVSize.texelWidth;
  14357. this._height.value = cubeUVSize.texelHeight;
  14358. this._maxMip.value = cubeUVSize.maxMip;
  14359. }
  14360. updateBefore() {
  14361. let pmrem = this._pmrem;
  14362. const pmremVersion = pmrem ? pmrem.pmremVersion : - 1;
  14363. const texture = this._value;
  14364. if ( pmremVersion !== texture.pmremVersion ) {
  14365. if ( texture.isPMREMTexture === true ) {
  14366. pmrem = texture;
  14367. } else {
  14368. pmrem = _getPMREMFromTexture( texture );
  14369. }
  14370. if ( pmrem !== null ) {
  14371. this._pmrem = pmrem;
  14372. this.updateFromTexture( pmrem );
  14373. }
  14374. }
  14375. }
  14376. setup( builder ) {
  14377. if ( _generator === null ) {
  14378. _generator = builder.createPMREMGenerator();
  14379. }
  14380. //
  14381. this.updateBefore( builder );
  14382. //
  14383. let uvNode = this.uvNode;
  14384. if ( uvNode === null && builder.context.getUV ) {
  14385. uvNode = builder.context.getUV( this );
  14386. }
  14387. //
  14388. const texture = this.value;
  14389. if ( builder.renderer.coordinateSystem === WebGLCoordinateSystem && texture.isPMREMTexture !== true && texture.isRenderTargetTexture === true ) {
  14390. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  14391. }
  14392. uvNode = vec3( uvNode.x, uvNode.y.negate(), uvNode.z );
  14393. //
  14394. let levelNode = this.levelNode;
  14395. if ( levelNode === null && builder.context.getTextureLevel ) {
  14396. levelNode = builder.context.getTextureLevel( this );
  14397. }
  14398. //
  14399. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  14400. }
  14401. }
  14402. /**
  14403. * Returns `true` if the given cube map image has been fully loaded.
  14404. *
  14405. * @private
  14406. * @param {Array<(Image|Object)>} image - The cube map image.
  14407. * @return {Boolean} Whether the given cube map is ready or not.
  14408. */
  14409. function isCubeMapReady( image ) {
  14410. if ( image === null || image === undefined ) return false;
  14411. let count = 0;
  14412. const length = 6;
  14413. for ( let i = 0; i < length; i ++ ) {
  14414. if ( image[ i ] !== undefined ) count ++;
  14415. }
  14416. return count === length;
  14417. }
  14418. /**
  14419. * Returns `true` if the given equirectangular image has been fully loaded.
  14420. *
  14421. * @private
  14422. * @param {(Image|Object)} image - The equirectangular image.
  14423. * @return {Boolean} Whether the given cube map is ready or not.
  14424. */
  14425. function isEquirectangularMapReady( image ) {
  14426. if ( image === null || image === undefined ) return false;
  14427. return image.height > 0;
  14428. }
  14429. /**
  14430. * TSL function for creating a PMREM node.
  14431. *
  14432. * @function
  14433. * @param {Texture} value - The input texture.
  14434. * @param {Node<vec2>} [uvNode=null] - The uv node.
  14435. * @param {Node<float>} [levelNode=null] - The level node.
  14436. * @returns {PMREMNode}
  14437. */
  14438. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode );
  14439. const _envNodeCache = new WeakMap();
  14440. /**
  14441. * Represents a physical model for Image-based lighting (IBL). The environment
  14442. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  14443. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  14444. *
  14445. * @augments LightingNode
  14446. */
  14447. class EnvironmentNode extends LightingNode {
  14448. static get type() {
  14449. return 'EnvironmentNode';
  14450. }
  14451. /**
  14452. * Constructs a new environment node.
  14453. *
  14454. * @param {Node} [envNode=null] - A node representing the environment.
  14455. */
  14456. constructor( envNode = null ) {
  14457. super();
  14458. /**
  14459. * A node representing the environment.
  14460. *
  14461. * @type {Node?}
  14462. * @default null
  14463. */
  14464. this.envNode = envNode;
  14465. }
  14466. setup( builder ) {
  14467. const { material } = builder;
  14468. let envNode = this.envNode;
  14469. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14470. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14471. let cacheEnvNode = _envNodeCache.get( value );
  14472. if ( cacheEnvNode === undefined ) {
  14473. cacheEnvNode = pmremTexture( value );
  14474. _envNodeCache.set( value, cacheEnvNode );
  14475. }
  14476. envNode = cacheEnvNode;
  14477. }
  14478. //
  14479. const envMap = material.envMap;
  14480. const intensity = envMap ? reference( 'envMapIntensity', 'float', builder.material ) : reference( 'environmentIntensity', 'float', builder.scene ); // @TODO: Add materialEnvIntensity in MaterialNode
  14481. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  14482. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  14483. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( intensity );
  14484. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( intensity );
  14485. const isolateRadiance = cache( radiance );
  14486. const isolateIrradiance = cache( irradiance );
  14487. //
  14488. builder.context.radiance.addAssign( isolateRadiance );
  14489. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  14490. //
  14491. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  14492. if ( clearcoatRadiance ) {
  14493. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( intensity );
  14494. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  14495. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  14496. }
  14497. }
  14498. }
  14499. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  14500. let reflectVec = null;
  14501. return {
  14502. getUV: () => {
  14503. if ( reflectVec === null ) {
  14504. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  14505. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  14506. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  14507. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  14508. }
  14509. return reflectVec;
  14510. },
  14511. getTextureLevel: () => {
  14512. return roughnessNode;
  14513. }
  14514. };
  14515. };
  14516. const createIrradianceContext = ( normalWorldNode ) => {
  14517. return {
  14518. getUV: () => {
  14519. return normalWorldNode;
  14520. },
  14521. getTextureLevel: () => {
  14522. return float( 1.0 );
  14523. }
  14524. };
  14525. };
  14526. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  14527. /**
  14528. * Node material version of `MeshStandardMaterial`.
  14529. *
  14530. * @augments NodeMaterial
  14531. */
  14532. class MeshStandardNodeMaterial extends NodeMaterial {
  14533. static get type() {
  14534. return 'MeshStandardNodeMaterial';
  14535. }
  14536. /**
  14537. * Constructs a new mesh standard node material.
  14538. *
  14539. * @param {Object?} parameters - The configuration parameter.
  14540. */
  14541. constructor( parameters ) {
  14542. super();
  14543. /**
  14544. * This flag can be used for type testing.
  14545. *
  14546. * @type {Boolean}
  14547. * @readonly
  14548. * @default true
  14549. */
  14550. this.isMeshStandardNodeMaterial = true;
  14551. /**
  14552. * Set to `true` because standard materials react on lights.
  14553. *
  14554. * @type {Boolean}
  14555. * @default true
  14556. */
  14557. this.lights = true;
  14558. /**
  14559. * The emissive color of standard materials is by default inferred from the `emissive`,
  14560. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  14561. * overwrite the default and define the emissive color with a node instead.
  14562. *
  14563. * If you don't want to overwrite the emissive color but modify the existing
  14564. * value instead, use {@link module:MaterialNode.materialEmissive}.
  14565. *
  14566. * @type {Node<vec3>?}
  14567. * @default null
  14568. */
  14569. this.emissiveNode = null;
  14570. /**
  14571. * The metalness of standard materials is by default inferred from the `metalness`,
  14572. * and `metalnessMap` properties. This node property allows to
  14573. * overwrite the default and define the metalness with a node instead.
  14574. *
  14575. * If you don't want to overwrite the metalness but modify the existing
  14576. * value instead, use {@link module:MaterialNode.materialMetalness}.
  14577. *
  14578. * @type {Node<float>?}
  14579. * @default null
  14580. */
  14581. this.metalnessNode = null;
  14582. /**
  14583. * The roughness of standard materials is by default inferred from the `roughness`,
  14584. * and `roughnessMap` properties. This node property allows to
  14585. * overwrite the default and define the roughness with a node instead.
  14586. *
  14587. * If you don't want to overwrite the roughness but modify the existing
  14588. * value instead, use {@link module:MaterialNode.materialRoughness}.
  14589. *
  14590. * @type {Node<float>?}
  14591. * @default null
  14592. */
  14593. this.roughnessNode = null;
  14594. this.setDefaultValues( _defaultValues$6 );
  14595. this.setValues( parameters );
  14596. }
  14597. /**
  14598. * Overwritten since this type of material uses {@link EnvironmentNode}
  14599. * to implement the PBR (PMREM based) environment mapping. Besides, the
  14600. * method honors `Scene.environment`.
  14601. *
  14602. * @param {NodeBuilder} builder - The current node builder.
  14603. * @return {EnvironmentNode<vec3>?} The environment node.
  14604. */
  14605. setupEnvironment( builder ) {
  14606. let envNode = super.setupEnvironment( builder );
  14607. if ( envNode === null && builder.environmentNode ) {
  14608. envNode = builder.environmentNode;
  14609. }
  14610. return envNode ? new EnvironmentNode( envNode ) : null;
  14611. }
  14612. /**
  14613. * Setups the lighting model.
  14614. *
  14615. * @return {PhysicalLightingModel} The lighting model.
  14616. */
  14617. setupLightingModel( /*builder*/ ) {
  14618. return new PhysicalLightingModel();
  14619. }
  14620. /**
  14621. * Setups the specular related node variables.
  14622. */
  14623. setupSpecular() {
  14624. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  14625. specularColor.assign( specularColorNode );
  14626. specularF90.assign( 1.0 );
  14627. }
  14628. /**
  14629. * Setups the standard specific node variables.
  14630. *
  14631. * @param {NodeBuilder} builder - The current node builder.
  14632. */
  14633. setupVariants() {
  14634. // METALNESS
  14635. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  14636. metalness.assign( metalnessNode );
  14637. // ROUGHNESS
  14638. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  14639. roughnessNode = getRoughness( { roughness: roughnessNode } );
  14640. roughness.assign( roughnessNode );
  14641. // SPECULAR COLOR
  14642. this.setupSpecular();
  14643. // DIFFUSE COLOR
  14644. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  14645. }
  14646. copy( source ) {
  14647. this.emissiveNode = source.emissiveNode;
  14648. this.metalnessNode = source.metalnessNode;
  14649. this.roughnessNode = source.roughnessNode;
  14650. return super.copy( source );
  14651. }
  14652. }
  14653. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  14654. /**
  14655. * Node material version of `MeshPhysicalMaterial`.
  14656. *
  14657. * @augments MeshStandardNodeMaterial
  14658. */
  14659. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  14660. static get type() {
  14661. return 'MeshPhysicalNodeMaterial';
  14662. }
  14663. /**
  14664. * Constructs a new mesh physical node material.
  14665. *
  14666. * @param {Object?} parameters - The configuration parameter.
  14667. */
  14668. constructor( parameters ) {
  14669. super();
  14670. /**
  14671. * This flag can be used for type testing.
  14672. *
  14673. * @type {Boolean}
  14674. * @readonly
  14675. * @default true
  14676. */
  14677. this.isMeshPhysicalNodeMaterial = true;
  14678. /**
  14679. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  14680. * and `clearcoatMap` properties. This node property allows to overwrite the default
  14681. * and define the clearcoat with a node instead.
  14682. *
  14683. * If you don't want to overwrite the clearcoat but modify the existing
  14684. * value instead, use {@link module:MaterialNode.materialClearcoat}.
  14685. *
  14686. * @type {Node<float>?}
  14687. * @default null
  14688. */
  14689. this.clearcoatNode = null;
  14690. /**
  14691. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  14692. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  14693. * and define the clearcoat roughness with a node instead.
  14694. *
  14695. * If you don't want to overwrite the clearcoat roughness but modify the existing
  14696. * value instead, use {@link module:MaterialNode.materialClearcoatRoughness}.
  14697. *
  14698. * @type {Node<float>?}
  14699. * @default null
  14700. */
  14701. this.clearcoatRoughnessNode = null;
  14702. /**
  14703. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  14704. * property. This node property allows to overwrite the default
  14705. * and define the clearcoat normal with a node instead.
  14706. *
  14707. * If you don't want to overwrite the clearcoat normal but modify the existing
  14708. * value instead, use {@link module:MaterialNode.materialClearcoatNormal}.
  14709. *
  14710. * @type {Node<vec3>?}
  14711. * @default null
  14712. */
  14713. this.clearcoatNormalNode = null;
  14714. /**
  14715. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  14716. * and `sheenColorMap` properties. This node property allows to overwrite the default
  14717. * and define the sheen with a node instead.
  14718. *
  14719. * If you don't want to overwrite the sheen but modify the existing
  14720. * value instead, use {@link module:MaterialNode.materialSheen}.
  14721. *
  14722. * @type {Node<vec3>?}
  14723. * @default null
  14724. */
  14725. this.sheenNode = null;
  14726. /**
  14727. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  14728. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  14729. * and define the sheen roughness with a node instead.
  14730. *
  14731. * If you don't want to overwrite the sheen roughness but modify the existing
  14732. * value instead, use {@link module:MaterialNode.materialSheenRoughness}.
  14733. *
  14734. * @type {Node<float>?}
  14735. * @default null
  14736. */
  14737. this.sheenRoughnessNode = null;
  14738. /**
  14739. * The iridescence of physical materials is by default inferred from the `iridescence`
  14740. * property. This node property allows to overwrite the default
  14741. * and define the iridescence with a node instead.
  14742. *
  14743. * If you don't want to overwrite the iridescence but modify the existing
  14744. * value instead, use {@link module:MaterialNode.materialIridescence}.
  14745. *
  14746. * @type {Node<float>?}
  14747. * @default null
  14748. */
  14749. this.iridescenceNode = null;
  14750. /**
  14751. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  14752. * property. This node property allows to overwrite the default
  14753. * and define the iridescence IOR with a node instead.
  14754. *
  14755. * If you don't want to overwrite the iridescence IOR but modify the existing
  14756. * value instead, use {@link module:MaterialNode.materialIridescenceIOR}.
  14757. *
  14758. * @type {Node<float>?}
  14759. * @default null
  14760. */
  14761. this.iridescenceIORNode = null;
  14762. /**
  14763. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  14764. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  14765. * and define the iridescence thickness with a node instead.
  14766. *
  14767. * If you don't want to overwrite the iridescence thickness but modify the existing
  14768. * value instead, use {@link module:MaterialNode.materialIridescenceThickness}.
  14769. *
  14770. * @type {Node<float>?}
  14771. * @default null
  14772. */
  14773. this.iridescenceThicknessNode = null;
  14774. /**
  14775. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  14776. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  14777. * and define the specular intensity with a node instead.
  14778. *
  14779. * If you don't want to overwrite the specular intensity but modify the existing
  14780. * value instead, use {@link module:MaterialNode.materialSpecularIntensity}.
  14781. *
  14782. * @type {Node<float>?}
  14783. * @default null
  14784. */
  14785. this.specularIntensityNode = null;
  14786. /**
  14787. * The specular color of physical materials is by default inferred from the `specularColor`
  14788. * and `specularColorMap` properties. This node property allows to overwrite the default
  14789. * and define the specular color with a node instead.
  14790. *
  14791. * If you don't want to overwrite the specular color but modify the existing
  14792. * value instead, use {@link module:MaterialNode.materialSpecularColor}.
  14793. *
  14794. * @type {Node<vec3>?}
  14795. * @default null
  14796. */
  14797. this.specularColorNode = null;
  14798. /**
  14799. * The ior of physical materials is by default inferred from the `ior`
  14800. * property. This node property allows to overwrite the default
  14801. * and define the ior with a node instead.
  14802. *
  14803. * If you don't want to overwrite the ior but modify the existing
  14804. * value instead, use {@link module:MaterialNode.materialIOR}.
  14805. *
  14806. * @type {Node<float>?}
  14807. * @default null
  14808. */
  14809. this.iorNode = null;
  14810. /**
  14811. * The transmission of physical materials is by default inferred from the `transmission` and
  14812. * `transmissionMap` properties. This node property allows to overwrite the default
  14813. * and define the transmission with a node instead.
  14814. *
  14815. * If you don't want to overwrite the transmission but modify the existing
  14816. * value instead, use {@link module:MaterialNode.materialTransmission}.
  14817. *
  14818. * @type {Node<float>?}
  14819. * @default null
  14820. */
  14821. this.transmissionNode = null;
  14822. /**
  14823. * The thickness of physical materials is by default inferred from the `thickness` and
  14824. * `thicknessMap` properties. This node property allows to overwrite the default
  14825. * and define the thickness with a node instead.
  14826. *
  14827. * If you don't want to overwrite the thickness but modify the existing
  14828. * value instead, use {@link module:MaterialNode.materialThickness}.
  14829. *
  14830. * @type {Node<float>?}
  14831. * @default null
  14832. */
  14833. this.thicknessNode = null;
  14834. /**
  14835. * The attenuation distance of physical materials is by default inferred from the
  14836. * `attenuationDistance` property. This node property allows to overwrite the default
  14837. * and define the attenuation distance with a node instead.
  14838. *
  14839. * If you don't want to overwrite the attenuation distance but modify the existing
  14840. * value instead, use {@link module:MaterialNode.materialAttenuationDistance}.
  14841. *
  14842. * @type {Node<float>?}
  14843. * @default null
  14844. */
  14845. this.attenuationDistanceNode = null;
  14846. /**
  14847. * The attenuation color of physical materials is by default inferred from the
  14848. * `attenuationColor` property. This node property allows to overwrite the default
  14849. * and define the attenuation color with a node instead.
  14850. *
  14851. * If you don't want to overwrite the attenuation color but modify the existing
  14852. * value instead, use {@link module:MaterialNode.materialAttenuationColor}.
  14853. *
  14854. * @type {Node<vec3>?}
  14855. * @default null
  14856. */
  14857. this.attenuationColorNode = null;
  14858. /**
  14859. * The dispersion of physical materials is by default inferred from the
  14860. * `dispersion` property. This node property allows to overwrite the default
  14861. * and define the dispersion with a node instead.
  14862. *
  14863. * If you don't want to overwrite the dispersion but modify the existing
  14864. * value instead, use {@link module:MaterialNode.materialDispersion}.
  14865. *
  14866. * @type {Node<float>?}
  14867. * @default null
  14868. */
  14869. this.dispersionNode = null;
  14870. /**
  14871. * The anisotropy of physical materials is by default inferred from the
  14872. * `anisotropy` property. This node property allows to overwrite the default
  14873. * and define the anisotropy with a node instead.
  14874. *
  14875. * If you don't want to overwrite the anisotropy but modify the existing
  14876. * value instead, use {@link module:MaterialNode.materialAnisotropy}.
  14877. *
  14878. * @type {Node<float>?}
  14879. * @default null
  14880. */
  14881. this.anisotropyNode = null;
  14882. this.setDefaultValues( _defaultValues$5 );
  14883. this.setValues( parameters );
  14884. }
  14885. /**
  14886. * Whether the lighting model should use clearcoat or not.
  14887. *
  14888. * @type {Boolean}
  14889. * @default true
  14890. */
  14891. get useClearcoat() {
  14892. return this.clearcoat > 0 || this.clearcoatNode !== null;
  14893. }
  14894. /**
  14895. * Whether the lighting model should use iridescence or not.
  14896. *
  14897. * @type {Boolean}
  14898. * @default true
  14899. */
  14900. get useIridescence() {
  14901. return this.iridescence > 0 || this.iridescenceNode !== null;
  14902. }
  14903. /**
  14904. * Whether the lighting model should use sheen or not.
  14905. *
  14906. * @type {Boolean}
  14907. * @default true
  14908. */
  14909. get useSheen() {
  14910. return this.sheen > 0 || this.sheenNode !== null;
  14911. }
  14912. /**
  14913. * Whether the lighting model should use anisotropy or not.
  14914. *
  14915. * @type {Boolean}
  14916. * @default true
  14917. */
  14918. get useAnisotropy() {
  14919. return this.anisotropy > 0 || this.anisotropyNode !== null;
  14920. }
  14921. /**
  14922. * Whether the lighting model should use transmission or not.
  14923. *
  14924. * @type {Boolean}
  14925. * @default true
  14926. */
  14927. get useTransmission() {
  14928. return this.transmission > 0 || this.transmissionNode !== null;
  14929. }
  14930. /**
  14931. * Whether the lighting model should use dispersion or not.
  14932. *
  14933. * @type {Boolean}
  14934. * @default true
  14935. */
  14936. get useDispersion() {
  14937. return this.dispersion > 0 || this.dispersionNode !== null;
  14938. }
  14939. /**
  14940. * Setups the specular related node variables.
  14941. */
  14942. setupSpecular() {
  14943. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  14944. ior.assign( iorNode );
  14945. specularColor.assign( mix( min$1( pow2( ior.sub( 1.0 ).div( ior.add( 1.0 ) ) ).mul( materialSpecularColor ), vec3( 1.0 ) ).mul( materialSpecularIntensity ), diffuseColor.rgb, metalness ) );
  14946. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  14947. }
  14948. /**
  14949. * Setups the lighting model.
  14950. *
  14951. * @return {PhysicalLightingModel} The lighting model.
  14952. */
  14953. setupLightingModel( /*builder*/ ) {
  14954. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  14955. }
  14956. /**
  14957. * Setups the physical specific node variables.
  14958. *
  14959. * @param {NodeBuilder} builder - The current node builder.
  14960. */
  14961. setupVariants( builder ) {
  14962. super.setupVariants( builder );
  14963. // CLEARCOAT
  14964. if ( this.useClearcoat ) {
  14965. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  14966. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  14967. clearcoat.assign( clearcoatNode );
  14968. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  14969. }
  14970. // SHEEN
  14971. if ( this.useSheen ) {
  14972. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  14973. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  14974. sheen.assign( sheenNode );
  14975. sheenRoughness.assign( sheenRoughnessNode );
  14976. }
  14977. // IRIDESCENCE
  14978. if ( this.useIridescence ) {
  14979. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  14980. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  14981. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  14982. iridescence.assign( iridescenceNode );
  14983. iridescenceIOR.assign( iridescenceIORNode );
  14984. iridescenceThickness.assign( iridescenceThicknessNode );
  14985. }
  14986. // ANISOTROPY
  14987. if ( this.useAnisotropy ) {
  14988. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  14989. anisotropy.assign( anisotropyV.length() );
  14990. If( anisotropy.equal( 0.0 ), () => {
  14991. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  14992. } ).Else( () => {
  14993. anisotropyV.divAssign( vec2( anisotropy ) );
  14994. anisotropy.assign( anisotropy.saturate() );
  14995. } );
  14996. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  14997. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  14998. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  14999. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  15000. }
  15001. // TRANSMISSION
  15002. if ( this.useTransmission ) {
  15003. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  15004. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  15005. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  15006. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  15007. transmission.assign( transmissionNode );
  15008. thickness.assign( thicknessNode );
  15009. attenuationDistance.assign( attenuationDistanceNode );
  15010. attenuationColor.assign( attenuationColorNode );
  15011. if ( this.useDispersion ) {
  15012. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  15013. dispersion.assign( dispersionNode );
  15014. }
  15015. }
  15016. }
  15017. /**
  15018. * Setups the clearcoat normal node.
  15019. *
  15020. * @return {Node<vec3>} The clearcoat normal.
  15021. */
  15022. setupClearcoatNormal() {
  15023. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  15024. }
  15025. setup( builder ) {
  15026. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  15027. super.setup( builder );
  15028. }
  15029. copy( source ) {
  15030. this.clearcoatNode = source.clearcoatNode;
  15031. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  15032. this.clearcoatNormalNode = source.clearcoatNormalNode;
  15033. this.sheenNode = source.sheenNode;
  15034. this.sheenRoughnessNode = source.sheenRoughnessNode;
  15035. this.iridescenceNode = source.iridescenceNode;
  15036. this.iridescenceIORNode = source.iridescenceIORNode;
  15037. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  15038. this.specularIntensityNode = source.specularIntensityNode;
  15039. this.specularColorNode = source.specularColorNode;
  15040. this.transmissionNode = source.transmissionNode;
  15041. this.thicknessNode = source.thicknessNode;
  15042. this.attenuationDistanceNode = source.attenuationDistanceNode;
  15043. this.attenuationColorNode = source.attenuationColorNode;
  15044. this.dispersionNode = source.dispersionNode;
  15045. this.anisotropyNode = source.anisotropyNode;
  15046. return super.copy( source );
  15047. }
  15048. }
  15049. /** @module MeshSSSNodeMaterial **/
  15050. /**
  15051. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  15052. *
  15053. * @augments PhysicalLightingModel
  15054. */
  15055. class SSSLightingModel extends PhysicalLightingModel {
  15056. /**
  15057. * Constructs a new physical lighting model.
  15058. *
  15059. * @param {Boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15060. * @param {Boolean} [sheen=false] - Whether sheen is supported or not.
  15061. * @param {Boolean} [iridescence=false] - Whether iridescence is supported or not.
  15062. * @param {Boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15063. * @param {Boolean} [transmission=false] - Whether transmission is supported or not.
  15064. * @param {Boolean} [dispersion=false] - Whether dispersion is supported or not.
  15065. * @param {Boolean} [sss=false] - Whether SSS is supported or not.
  15066. */
  15067. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  15068. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  15069. /**
  15070. * Whether the lighting model should use SSS or not.
  15071. *
  15072. * @type {Boolean}
  15073. * @default false
  15074. */
  15075. this.useSSS = sss;
  15076. }
  15077. /**
  15078. * Extends the default implementation with a SSS term.
  15079. *
  15080. * Reference: [Approximating Translucency for a Fast, Cheap and Convincing Subsurface Scattering Look]{@link https://colinbarrebrisebois.com/2011/03/07/gdc-2011-approximating-translucency-for-a-fast-cheap-and-convincing-subsurface-scattering-look/}
  15081. *
  15082. * @param {Object} input - The input data.
  15083. * @param {StackNode} stack - The current stack.
  15084. * @param {NodeBuilder} builder - The current node builder.
  15085. */
  15086. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15087. if ( this.useSSS === true ) {
  15088. const material = builder.material;
  15089. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  15090. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  15091. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  15092. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  15093. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  15094. }
  15095. super.direct( { lightDirection, lightColor, reflectedLight }, stack, builder );
  15096. }
  15097. }
  15098. /**
  15099. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  15100. * that implements a Subsurface scattering (SSS) term.
  15101. *
  15102. * @augments MeshPhysicalNodeMaterial
  15103. */
  15104. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  15105. static get type() {
  15106. return 'MeshSSSNodeMaterial';
  15107. }
  15108. /**
  15109. * Constructs a new mesh SSS node material.
  15110. *
  15111. * @param {Object?} parameters - The configuration parameter.
  15112. */
  15113. constructor( parameters ) {
  15114. super( parameters );
  15115. /**
  15116. * Represents the thickness color.
  15117. *
  15118. * @type {Node<vec3>?}
  15119. * @default null
  15120. */
  15121. this.thicknessColorNode = null;
  15122. /**
  15123. * Represents the distortion factor.
  15124. *
  15125. * @type {Node<float>?}
  15126. */
  15127. this.thicknessDistortionNode = float( 0.1 );
  15128. /**
  15129. * Represents the thickness ambient factor.
  15130. *
  15131. * @type {Node<float>?}
  15132. */
  15133. this.thicknessAmbientNode = float( 0.0 );
  15134. /**
  15135. * Represents the thickness attenuation.
  15136. *
  15137. * @type {Node<float>?}
  15138. */
  15139. this.thicknessAttenuationNode = float( .1 );
  15140. /**
  15141. * Represents the thickness power.
  15142. *
  15143. * @type {Node<float>?}
  15144. */
  15145. this.thicknessPowerNode = float( 2.0 );
  15146. /**
  15147. * Represents the thickness scale.
  15148. *
  15149. * @type {Node<float>?}
  15150. */
  15151. this.thicknessScaleNode = float( 10.0 );
  15152. }
  15153. /**
  15154. * Whether the lighting model should use SSS or not.
  15155. *
  15156. * @type {Boolean}
  15157. * @default true
  15158. */
  15159. get useSSS() {
  15160. return this.thicknessColorNode !== null;
  15161. }
  15162. /**
  15163. * Setups the lighting model.
  15164. *
  15165. * @return {SSSLightingModel} The lighting model.
  15166. */
  15167. setupLightingModel( /*builder*/ ) {
  15168. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  15169. }
  15170. copy( source ) {
  15171. this.thicknessColorNode = source.thicknessColorNode;
  15172. this.thicknessDistortionNode = source.thicknessDistortionNode;
  15173. this.thicknessAmbientNode = source.thicknessAmbientNode;
  15174. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  15175. this.thicknessPowerNode = source.thicknessPowerNode;
  15176. this.thicknessScaleNode = source.thicknessScaleNode;
  15177. return super.copy( source );
  15178. }
  15179. }
  15180. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  15181. // dotNL will be from -1.0 to 1.0
  15182. const dotNL = normal.dot( lightDirection );
  15183. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  15184. if ( builder.material.gradientMap ) {
  15185. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  15186. return vec3( gradientMap.r );
  15187. } else {
  15188. const fw = coord.fwidth().mul( 0.5 );
  15189. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  15190. }
  15191. } );
  15192. /**
  15193. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  15194. *
  15195. * @augments LightingModel
  15196. */
  15197. class ToonLightingModel extends LightingModel {
  15198. /**
  15199. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  15200. * reduced to a small number of discrete shades to create a comic-like, flat look.
  15201. *
  15202. * @param {Object} input - The input data.
  15203. * @param {StackNode} stack - The current stack.
  15204. * @param {NodeBuilder} builder - The current node builder.
  15205. */
  15206. direct( { lightDirection, lightColor, reflectedLight }, stack, builder ) {
  15207. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  15208. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15209. }
  15210. /**
  15211. * Implements the indirect lighting.
  15212. *
  15213. * @param {ContextNode} input - The current node context.
  15214. * @param {StackNode} stack - The current stack.
  15215. * @param {NodeBuilder} builder - The current node builder.
  15216. */
  15217. indirect( { ambientOcclusion, irradiance, reflectedLight } ) {
  15218. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15219. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15220. }
  15221. }
  15222. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  15223. /**
  15224. * Node material version of `MeshToonMaterial`.
  15225. *
  15226. * @augments NodeMaterial
  15227. */
  15228. class MeshToonNodeMaterial extends NodeMaterial {
  15229. static get type() {
  15230. return 'MeshToonNodeMaterial';
  15231. }
  15232. /**
  15233. * Constructs a new mesh toon node material.
  15234. *
  15235. * @param {Object?} parameters - The configuration parameter.
  15236. */
  15237. constructor( parameters ) {
  15238. super();
  15239. /**
  15240. * This flag can be used for type testing.
  15241. *
  15242. * @type {Boolean}
  15243. * @readonly
  15244. * @default true
  15245. */
  15246. this.isMeshToonNodeMaterial = true;
  15247. /**
  15248. * Set to `true` because toon materials react on lights.
  15249. *
  15250. * @type {Boolean}
  15251. * @default true
  15252. */
  15253. this.lights = true;
  15254. this.setDefaultValues( _defaultValues$4 );
  15255. this.setValues( parameters );
  15256. }
  15257. /**
  15258. * Setups the lighting model.
  15259. *
  15260. * @return {ToonLightingModel} The lighting model.
  15261. */
  15262. setupLightingModel( /*builder*/ ) {
  15263. return new ToonLightingModel();
  15264. }
  15265. }
  15266. /** @module MatcapUVNode **/
  15267. /**
  15268. * Can be used to compute texture coordinates for projecting a
  15269. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  15270. *
  15271. * @augments TempNode
  15272. */
  15273. class MatcapUVNode extends TempNode {
  15274. static get type() {
  15275. return 'MatcapUVNode';
  15276. }
  15277. /**
  15278. * Constructs a new matcap uv node.
  15279. */
  15280. constructor() {
  15281. super( 'vec2' );
  15282. }
  15283. setup() {
  15284. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  15285. const y = positionViewDirection.cross( x );
  15286. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  15287. }
  15288. }
  15289. /**
  15290. * TSL function for creating a matcap uv node.
  15291. *
  15292. * @function
  15293. * @returns {MatcapUVNode}
  15294. */
  15295. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  15296. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  15297. /**
  15298. * Node material version of `MeshMatcapMaterial`.
  15299. *
  15300. * @augments NodeMaterial
  15301. */
  15302. class MeshMatcapNodeMaterial extends NodeMaterial {
  15303. static get type() {
  15304. return 'MeshMatcapNodeMaterial';
  15305. }
  15306. /**
  15307. * Constructs a new mesh normal node material.
  15308. *
  15309. * @param {Object?} parameters - The configuration parameter.
  15310. */
  15311. constructor( parameters ) {
  15312. super();
  15313. /**
  15314. * This flag can be used for type testing.
  15315. *
  15316. * @type {Boolean}
  15317. * @readonly
  15318. * @default true
  15319. */
  15320. this.isMeshMatcapNodeMaterial = true;
  15321. this.setDefaultValues( _defaultValues$3 );
  15322. this.setValues( parameters );
  15323. }
  15324. /**
  15325. * Setups the matcap specific node variables.
  15326. *
  15327. * @param {NodeBuilder} builder - The current node builder.
  15328. */
  15329. setupVariants( builder ) {
  15330. const uv = matcapUV;
  15331. let matcapColor;
  15332. if ( builder.material.matcap ) {
  15333. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  15334. } else {
  15335. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  15336. }
  15337. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  15338. }
  15339. }
  15340. /** @module RotateNode **/
  15341. /**
  15342. * Applies a rotation to the given position node.
  15343. *
  15344. * @augments TempNode
  15345. */
  15346. class RotateNode extends TempNode {
  15347. static get type() {
  15348. return 'RotateNode';
  15349. }
  15350. /**
  15351. * Constructs a new rotate node.
  15352. *
  15353. * @param {Node} positionNode - The position node.
  15354. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15355. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15356. */
  15357. constructor( positionNode, rotationNode ) {
  15358. super();
  15359. /**
  15360. * The position node.
  15361. *
  15362. * @type {Node}
  15363. */
  15364. this.positionNode = positionNode;
  15365. /**
  15366. * Represents the rotation that is applied to the position node.
  15367. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15368. *
  15369. * @type {Node}
  15370. */
  15371. this.rotationNode = rotationNode;
  15372. }
  15373. /**
  15374. * The type of the {@link RotateNode#positionNode} defines the node's type.
  15375. *
  15376. * @param {NodeBuilder} builder - The current node builder.
  15377. * @return {String} The node's type.
  15378. */
  15379. getNodeType( builder ) {
  15380. return this.positionNode.getNodeType( builder );
  15381. }
  15382. setup( builder ) {
  15383. const { rotationNode, positionNode } = this;
  15384. const nodeType = this.getNodeType( builder );
  15385. if ( nodeType === 'vec2' ) {
  15386. const cosAngle = rotationNode.cos();
  15387. const sinAngle = rotationNode.sin();
  15388. const rotationMatrix = mat2(
  15389. cosAngle, sinAngle,
  15390. sinAngle.negate(), cosAngle
  15391. );
  15392. return rotationMatrix.mul( positionNode );
  15393. } else {
  15394. const rotation = rotationNode;
  15395. const rotationXMatrix = mat4( vec4( 1.0, 0.0, 0.0, 0.0 ), vec4( 0.0, cos( rotation.x ), sin( rotation.x ).negate(), 0.0 ), vec4( 0.0, sin( rotation.x ), cos( rotation.x ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  15396. const rotationYMatrix = mat4( vec4( cos( rotation.y ), 0.0, sin( rotation.y ), 0.0 ), vec4( 0.0, 1.0, 0.0, 0.0 ), vec4( sin( rotation.y ).negate(), 0.0, cos( rotation.y ), 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  15397. const rotationZMatrix = mat4( vec4( cos( rotation.z ), sin( rotation.z ).negate(), 0.0, 0.0 ), vec4( sin( rotation.z ), cos( rotation.z ), 0.0, 0.0 ), vec4( 0.0, 0.0, 1.0, 0.0 ), vec4( 0.0, 0.0, 0.0, 1.0 ) );
  15398. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  15399. }
  15400. }
  15401. }
  15402. /**
  15403. * TSL function for creating a rotate node.
  15404. *
  15405. * @function
  15406. * @param {Node} positionNode - The position node.
  15407. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  15408. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  15409. * @returns {RotateNode}
  15410. */
  15411. const rotate = /*@__PURE__*/ nodeProxy( RotateNode );
  15412. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  15413. /**
  15414. * Node material version of `SpriteMaterial`.
  15415. *
  15416. * @augments NodeMaterial
  15417. */
  15418. class SpriteNodeMaterial extends NodeMaterial {
  15419. static get type() {
  15420. return 'SpriteNodeMaterial';
  15421. }
  15422. /**
  15423. * Constructs a new sprite node material.
  15424. *
  15425. * @param {Object?} parameters - The configuration parameter.
  15426. */
  15427. constructor( parameters ) {
  15428. super();
  15429. /**
  15430. * This flag can be used for type testing.
  15431. *
  15432. * @type {Boolean}
  15433. * @readonly
  15434. * @default true
  15435. */
  15436. this.isSpriteNodeMaterial = true;
  15437. this._useSizeAttenuation = true;
  15438. /**
  15439. * This property makes it possible to define the position of the sprite with a
  15440. * node. That can be useful when the material is used with instanced rendering
  15441. * and node data are defined with an instanced attribute node:
  15442. * ```js
  15443. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  15444. * material.positionNode = instancedBufferAttribute( positionAttribute );
  15445. * ```
  15446. * Another possibility is to compute the instanced data with a compute shader:
  15447. * ```js
  15448. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  15449. * particleMaterial.positionNode = positionBuffer.toAttribute();
  15450. * ```
  15451. *
  15452. * @type {Node<vec2>?}
  15453. * @default null
  15454. */
  15455. this.positionNode = null;
  15456. /**
  15457. * The rotation of sprite materials is by default inferred from the `rotation`,
  15458. * property. This node property allows to overwrite the default and define
  15459. * the rotation with a node instead.
  15460. *
  15461. * If you don't want to overwrite the rotation but modify the existing
  15462. * value instead, use {@link module:MaterialNode.materialRotation}.
  15463. *
  15464. * @type {Node<float>?}
  15465. * @default null
  15466. */
  15467. this.rotationNode = null;
  15468. /**
  15469. * This node property provides an additional way to scale sprites next to
  15470. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  15471. * is multiplied with the scale value of this node in the vertex shader.
  15472. *
  15473. * @type {Node<vec2>?}
  15474. * @default null
  15475. */
  15476. this.scaleNode = null;
  15477. this.setDefaultValues( _defaultValues$2 );
  15478. this.setValues( parameters );
  15479. }
  15480. /**
  15481. * Setups the position node in view space. This method implements
  15482. * the sprite specific vertex shader.
  15483. *
  15484. * @param {NodeBuilder} builder - The current node builder.
  15485. * @return {Node<vec3>} The position in view space.
  15486. */
  15487. setupPositionView( builder ) {
  15488. const { object, camera } = builder;
  15489. const sizeAttenuation = this.sizeAttenuation;
  15490. const { positionNode, rotationNode, scaleNode } = this;
  15491. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  15492. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  15493. if ( scaleNode !== null ) {
  15494. scale = scale.mul( float( scaleNode ) );
  15495. }
  15496. if ( sizeAttenuation === false ) {
  15497. if ( camera.isPerspectiveCamera ) {
  15498. scale = scale.mul( mvPosition.z.negate() );
  15499. } else {
  15500. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  15501. scale = scale.mul( orthoScale.mul( 2 ) );
  15502. }
  15503. }
  15504. let alignedPosition = positionGeometry.xy;
  15505. if ( object.center && object.center.isVector2 === true ) {
  15506. const center = reference$1( 'center', 'vec2', object );
  15507. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  15508. }
  15509. alignedPosition = alignedPosition.mul( scale );
  15510. const rotation = float( rotationNode || materialRotation );
  15511. const rotatedPosition = rotate( alignedPosition, rotation );
  15512. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  15513. }
  15514. copy( source ) {
  15515. this.positionNode = source.positionNode;
  15516. this.rotationNode = source.rotationNode;
  15517. this.scaleNode = source.scaleNode;
  15518. return super.copy( source );
  15519. }
  15520. /**
  15521. * Whether to use size attenuation or not.
  15522. *
  15523. * @type {Boolean}
  15524. * @default true
  15525. */
  15526. get sizeAttenuation() {
  15527. return this._useSizeAttenuation;
  15528. }
  15529. set sizeAttenuation( value ) {
  15530. if ( this._useSizeAttenuation !== value ) {
  15531. this._useSizeAttenuation = value;
  15532. this.needsUpdate = true;
  15533. }
  15534. }
  15535. }
  15536. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  15537. /**
  15538. * Node material version of `PointsMaterial`.
  15539. *
  15540. * @augments NodeMaterial
  15541. */
  15542. class PointsNodeMaterial extends SpriteNodeMaterial {
  15543. static get type() {
  15544. return 'PointsNodeMaterial';
  15545. }
  15546. /**
  15547. * Constructs a new points node material.
  15548. *
  15549. * @param {Object?} parameters - The configuration parameter.
  15550. */
  15551. constructor( parameters ) {
  15552. super();
  15553. /**
  15554. * This node property provides an additional way to set the point size.
  15555. *
  15556. * @type {Node<vec2>?}
  15557. * @default null
  15558. */
  15559. this.sizeNode = null;
  15560. /**
  15561. * This flag can be used for type testing.
  15562. *
  15563. * @type {Boolean}
  15564. * @readonly
  15565. * @default true
  15566. */
  15567. this.isPointsNodeMaterial = true;
  15568. this.setDefaultValues( _defaultValues$1 );
  15569. this.setValues( parameters );
  15570. }
  15571. setupPositionView() {
  15572. const { positionNode } = this;
  15573. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  15574. }
  15575. setupVertex( builder ) {
  15576. const mvp = super.setupVertex( builder );
  15577. // skip further processing if the material is not a node material
  15578. if ( builder.material.isNodeMaterial !== true ) {
  15579. return mvp;
  15580. }
  15581. // ndc space
  15582. const { rotationNode, scaleNode, sizeNode } = this;
  15583. const alignedPosition = positionGeometry.xy.toVar();
  15584. const aspect = viewport.z.div( viewport.w );
  15585. // rotation
  15586. if ( rotationNode && rotationNode.isNode ) {
  15587. const rotation = float( rotationNode );
  15588. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  15589. }
  15590. // point size
  15591. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  15592. if ( this.sizeAttenuation === true ) {
  15593. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  15594. }
  15595. // scale
  15596. if ( scaleNode && scaleNode.isNode ) {
  15597. pointSize = pointSize.mul( vec2( scaleNode ) );
  15598. }
  15599. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  15600. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  15601. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  15602. // back to clip space
  15603. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  15604. //clipPos.xy += offset;
  15605. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  15606. return mvp;
  15607. }
  15608. /**
  15609. * Whether alpha to coverage should be used or not.
  15610. *
  15611. * @type {Boolean}
  15612. * @default true
  15613. */
  15614. get alphaToCoverage() {
  15615. return this._useAlphaToCoverage;
  15616. }
  15617. set alphaToCoverage( value ) {
  15618. if ( this._useAlphaToCoverage !== value ) {
  15619. this._useAlphaToCoverage = value;
  15620. this.needsUpdate = true;
  15621. }
  15622. }
  15623. }
  15624. /**
  15625. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  15626. *
  15627. * @augments LightingModel
  15628. */
  15629. class ShadowMaskModel extends LightingModel {
  15630. /**
  15631. * Constructs a new shadow mask model.
  15632. */
  15633. constructor() {
  15634. super();
  15635. /**
  15636. * The shadow mask node.
  15637. *
  15638. * @type {Node}
  15639. */
  15640. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  15641. }
  15642. /**
  15643. * Only used to save the shadow mask.
  15644. *
  15645. * @param {Object} input - The input data.
  15646. */
  15647. direct( { shadowMask } ) {
  15648. this.shadowNode.mulAssign( shadowMask );
  15649. }
  15650. /**
  15651. * Uses the shadow mask to produce the final color.
  15652. *
  15653. * @param {ContextNode} context - The current node context.
  15654. */
  15655. finish( context ) {
  15656. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  15657. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  15658. }
  15659. }
  15660. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  15661. /**
  15662. * Node material version of `ShadowMaterial`.
  15663. *
  15664. * @augments NodeMaterial
  15665. */
  15666. class ShadowNodeMaterial extends NodeMaterial {
  15667. static get type() {
  15668. return 'ShadowNodeMaterial';
  15669. }
  15670. /**
  15671. * Constructs a new shadow node material.
  15672. *
  15673. * @param {Object?} parameters - The configuration parameter.
  15674. */
  15675. constructor( parameters ) {
  15676. super();
  15677. /**
  15678. * This flag can be used for type testing.
  15679. *
  15680. * @type {Boolean}
  15681. * @readonly
  15682. * @default true
  15683. */
  15684. this.isShadowNodeMaterial = true;
  15685. /**
  15686. * Set to `true` because so it's possible to implement
  15687. * the shadow mask effect.
  15688. *
  15689. * @type {Boolean}
  15690. * @default true
  15691. */
  15692. this.lights = true;
  15693. this.setDefaultValues( _defaultValues );
  15694. this.setValues( parameters );
  15695. }
  15696. /**
  15697. * Setups the lighting model.
  15698. *
  15699. * @return {ShadowMaskModel} The lighting model.
  15700. */
  15701. setupLightingModel( /*builder*/ ) {
  15702. return new ShadowMaskModel();
  15703. }
  15704. }
  15705. /** @module Texture3DNode **/
  15706. const normal = Fn( ( { texture, uv } ) => {
  15707. const epsilon = 0.0001;
  15708. const ret = vec3().toVar();
  15709. If( uv.x.lessThan( epsilon ), () => {
  15710. ret.assign( vec3( 1, 0, 0 ) );
  15711. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  15712. ret.assign( vec3( 0, 1, 0 ) );
  15713. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  15714. ret.assign( vec3( 0, 0, 1 ) );
  15715. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  15716. ret.assign( vec3( - 1, 0, 0 ) );
  15717. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  15718. ret.assign( vec3( 0, - 1, 0 ) );
  15719. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  15720. ret.assign( vec3( 0, 0, - 1 ) );
  15721. } ).Else( () => {
  15722. const step = 0.01;
  15723. const x = texture.sample( uv.add( vec3( - step, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  15724. const y = texture.sample( uv.add( vec3( 0.0, - step, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  15725. const z = texture.sample( uv.add( vec3( 0.0, 0.0, - step ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  15726. ret.assign( vec3( x, y, z ) );
  15727. } );
  15728. return ret.normalize();
  15729. } );
  15730. /**
  15731. * This type of uniform node represents a 3D texture.
  15732. *
  15733. * @augments module:TextureNode~TextureNode
  15734. */
  15735. class Texture3DNode extends TextureNode {
  15736. static get type() {
  15737. return 'Texture3DNode';
  15738. }
  15739. /**
  15740. * Constructs a new 3D texture node.
  15741. *
  15742. * @param {Data3DTexture} value - The 3D texture.
  15743. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15744. * @param {Node<int>?} [levelNode=null] - The level node.
  15745. */
  15746. constructor( value, uvNode = null, levelNode = null ) {
  15747. super( value, uvNode, levelNode );
  15748. /**
  15749. * This flag can be used for type testing.
  15750. *
  15751. * @type {Boolean}
  15752. * @readonly
  15753. * @default true
  15754. */
  15755. this.isTexture3DNode = true;
  15756. }
  15757. /**
  15758. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  15759. *
  15760. * @param {NodeBuilder} builder - The current node builder.
  15761. * @return {String} The input type.
  15762. */
  15763. getInputType( /*builder*/ ) {
  15764. return 'texture3D';
  15765. }
  15766. /**
  15767. * Returns a default uv node which is in context of 3D textures a three-dimensional
  15768. * uv node.
  15769. *
  15770. * @return {Node<vec3>} The default uv node.
  15771. */
  15772. getDefaultUV() {
  15773. return vec3( 0.5, 0.5, 0.5 );
  15774. }
  15775. /**
  15776. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  15777. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  15778. *
  15779. * @param {Boolean} value - The update toggle.
  15780. */
  15781. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  15782. /**
  15783. * Overwrites the default implementation to return the unmodified uv node.
  15784. *
  15785. * @param {NodeBuilder} builder - The current node builder.
  15786. * @param {Node} uvNode - The uv node to setup.
  15787. * @return {Node} The unmodified uv node.
  15788. */
  15789. setupUV( builder, uvNode ) {
  15790. const texture = this.value;
  15791. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  15792. if ( this.sampler ) {
  15793. uvNode = uvNode.flipY();
  15794. } else {
  15795. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  15796. }
  15797. }
  15798. return uvNode;
  15799. }
  15800. /**
  15801. * Generates the uv code snippet.
  15802. *
  15803. * @param {NodeBuilder} builder - The current node builder.
  15804. * @param {Node} uvNode - The uv node to generate code for.
  15805. * @return {String} The generated code snippet.
  15806. */
  15807. generateUV( builder, uvNode ) {
  15808. return uvNode.build( builder, 'vec3' );
  15809. }
  15810. /**
  15811. * TODO.
  15812. *
  15813. * @param {Node<vec3>} uvNode - The uv node .
  15814. * @return {Node<vec3>} TODO.
  15815. */
  15816. normal( uvNode ) {
  15817. return normal( { texture: this, uv: uvNode } );
  15818. }
  15819. }
  15820. /**
  15821. * TSL function for creating a 3D texture node.
  15822. *
  15823. * @function
  15824. * @param {Data3DTexture} value - The 3D texture.
  15825. * @param {Node<vec2|vec3>?} [uvNode=null] - The uv node.
  15826. * @param {Node<int>?} [levelNode=null] - The level node.
  15827. * @returns {Texture3DNode}
  15828. */
  15829. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode );
  15830. /** @module VolumeNodeMaterial **/
  15831. /**
  15832. * Node material intended for volume rendering. The volumetric data are
  15833. * defined with an instance of {@link Data3DTexture}.
  15834. *
  15835. * @augments NodeMaterial
  15836. */
  15837. class VolumeNodeMaterial extends NodeMaterial {
  15838. static get type() {
  15839. return 'VolumeNodeMaterial';
  15840. }
  15841. /**
  15842. * Constructs a new volume node material.
  15843. *
  15844. * @param {Object?} parameters - The configuration parameter.
  15845. */
  15846. constructor( parameters ) {
  15847. super();
  15848. /**
  15849. * This flag can be used for type testing.
  15850. *
  15851. * @type {Boolean}
  15852. * @readonly
  15853. * @default true
  15854. */
  15855. this.isVolumeNodeMaterial = true;
  15856. /**
  15857. * The base color of the volume.
  15858. *
  15859. * @type {Color}
  15860. * @default 100
  15861. */
  15862. this.base = new Color( 0xffffff );
  15863. /**
  15864. * A 3D data texture holding the volumetric data.
  15865. *
  15866. * @type {Data3DTexture?}
  15867. * @default null
  15868. */
  15869. this.map = null;
  15870. /**
  15871. * This number of samples for each ray that hits the mesh's surface
  15872. * and travels through the volume.
  15873. *
  15874. * @type {Number}
  15875. * @default 100
  15876. */
  15877. this.steps = 100;
  15878. /**
  15879. * Callback for {@link VolumeNodeMaterial#testNode}.
  15880. *
  15881. * @callback testNodeCallback
  15882. * @param {Data3DTexture<float>} map - The 3D texture.
  15883. * @param {Node<float>} mapValue - The sampled value inside the volume.
  15884. * @param {Node<vec3>} probe - The probe which is the entry point of the ray on the mesh's surface.
  15885. * @param {Node<vec4>} finalColor - The final color.
  15886. */
  15887. /**
  15888. * The volume rendering of this material works by shooting rays
  15889. * from the camera position through each fragment of the mesh's
  15890. * surface and sample the inner volume in a raymarching fashion
  15891. * multiple times.
  15892. *
  15893. * This node can be used to assign a callback function of type `Fn`
  15894. * that will be executed per sample. The callback receives the
  15895. * texture, the sampled texture value as well as position on the surface
  15896. * where the rays enters the volume. The last parameter is a color
  15897. * that allows the callback to determine the final color.
  15898. *
  15899. * @type {testNodeCallback?}
  15900. * @default null
  15901. */
  15902. this.testNode = null;
  15903. this.setValues( parameters );
  15904. }
  15905. /**
  15906. * Setups the vertex and fragment stage of this node material.
  15907. *
  15908. * @param {NodeBuilder} builder - The current node builder.
  15909. */
  15910. setup( builder ) {
  15911. const map = texture3D( this.map, null, 0 );
  15912. const hitBox = Fn( ( { orig, dir } ) => {
  15913. const box_min = vec3( - 0.5 );
  15914. const box_max = vec3( 0.5 );
  15915. const inv_dir = dir.reciprocal();
  15916. const tmin_tmp = box_min.sub( orig ).mul( inv_dir );
  15917. const tmax_tmp = box_max.sub( orig ).mul( inv_dir );
  15918. const tmin = min$1( tmin_tmp, tmax_tmp );
  15919. const tmax = max$1( tmin_tmp, tmax_tmp );
  15920. const t0 = max$1( tmin.x, max$1( tmin.y, tmin.z ) );
  15921. const t1 = min$1( tmax.x, min$1( tmax.y, tmax.z ) );
  15922. return vec2( t0, t1 );
  15923. } );
  15924. this.fragmentNode = Fn( () => {
  15925. const vOrigin = varying( vec3( modelWorldMatrixInverse.mul( vec4( cameraPosition, 1.0 ) ) ) );
  15926. const vDirection = varying( positionGeometry.sub( vOrigin ) );
  15927. const rayDir = vDirection.normalize();
  15928. const bounds = vec2( hitBox( { orig: vOrigin, dir: rayDir } ) ).toVar();
  15929. bounds.x.greaterThan( bounds.y ).discard();
  15930. bounds.assign( vec2( max$1( bounds.x, 0.0 ), bounds.y ) );
  15931. const p = vec3( vOrigin.add( bounds.x.mul( rayDir ) ) ).toVar();
  15932. const inc = vec3( rayDir.abs().reciprocal() ).toVar();
  15933. const delta = float( min$1( inc.x, min$1( inc.y, inc.z ) ) ).toVar( 'delta' ); // used 'delta' name in loop
  15934. delta.divAssign( materialReference( 'steps', 'float' ) );
  15935. const ac = vec4( materialReference( 'base', 'color' ), 0.0 ).toVar();
  15936. Loop( { type: 'float', start: bounds.x, end: bounds.y, update: '+= delta' }, () => {
  15937. const d = property( 'float', 'd' ).assign( map.sample( p.add( 0.5 ) ).r );
  15938. if ( this.testNode !== null ) {
  15939. this.testNode( { map: map, mapValue: d, probe: p, finalColor: ac } ).append();
  15940. } else {
  15941. // default to show surface of mesh
  15942. ac.a.assign( 1 );
  15943. Break();
  15944. }
  15945. p.addAssign( rayDir.mul( delta ) );
  15946. } );
  15947. ac.a.equal( 0 ).discard();
  15948. return vec4( ac );
  15949. } )();
  15950. super.setup( builder );
  15951. }
  15952. }
  15953. /**
  15954. * This module manages the internal animation loop of the renderer.
  15955. *
  15956. * @private
  15957. */
  15958. class Animation {
  15959. /**
  15960. * Constructs a new animation loop management component.
  15961. *
  15962. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  15963. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  15964. */
  15965. constructor( nodes, info ) {
  15966. /**
  15967. * Renderer component for managing nodes related logic.
  15968. *
  15969. * @type {Nodes}
  15970. */
  15971. this.nodes = nodes;
  15972. /**
  15973. * Renderer component for managing metrics and monitoring data.
  15974. *
  15975. * @type {Info}
  15976. */
  15977. this.info = info;
  15978. /**
  15979. * A reference to the context from `requestAnimationFrame()` can
  15980. * be called (usually `window`).
  15981. *
  15982. * @type {Window|XRSession}
  15983. */
  15984. this._context = self;
  15985. /**
  15986. * The user-defined animation loop.
  15987. *
  15988. * @type {Function?}
  15989. * @default null
  15990. */
  15991. this._animationLoop = null;
  15992. /**
  15993. * The requestId which is returned from the `requestAnimationFrame()` call.
  15994. * Can be used to cancel the stop the animation loop.
  15995. *
  15996. * @type {Number?}
  15997. * @default null
  15998. */
  15999. this._requestId = null;
  16000. }
  16001. /**
  16002. * Starts the internal animation loop.
  16003. */
  16004. start() {
  16005. const update = ( time, frame ) => {
  16006. this._requestId = this._context.requestAnimationFrame( update );
  16007. if ( this.info.autoReset === true ) this.info.reset();
  16008. this.nodes.nodeFrame.update();
  16009. this.info.frame = this.nodes.nodeFrame.frameId;
  16010. if ( this._animationLoop !== null ) this._animationLoop( time, frame );
  16011. };
  16012. update();
  16013. }
  16014. /**
  16015. * Stops the internal animation loop.
  16016. */
  16017. stop() {
  16018. this._context.cancelAnimationFrame( this._requestId );
  16019. this._requestId = null;
  16020. }
  16021. /**
  16022. * Returns the user-level animation loop.
  16023. *
  16024. * @return {Function} The animation loop.
  16025. */
  16026. getAnimationLoop() {
  16027. return this._animationLoop;
  16028. }
  16029. /**
  16030. * Defines the user-level animation loop.
  16031. *
  16032. * @param {Function} callback - The animation loop.
  16033. */
  16034. setAnimationLoop( callback ) {
  16035. this._animationLoop = callback;
  16036. }
  16037. /**
  16038. * Returns the animation context.
  16039. *
  16040. * @return {Window|XRSession} The animation context.
  16041. */
  16042. getContext() {
  16043. return this._context;
  16044. }
  16045. /**
  16046. * Defines the context in which `requestAnimationFrame()` is executed.
  16047. *
  16048. * @param {Window|XRSession} context - The context to set.
  16049. */
  16050. setContext( context ) {
  16051. this._context = context;
  16052. }
  16053. /**
  16054. * Frees all internal resources and stops the animation loop.
  16055. */
  16056. dispose() {
  16057. this.stop();
  16058. }
  16059. }
  16060. /**
  16061. * Data structure for the renderer. It allows defining values
  16062. * with chained, hierarchical keys. Keys are meant to be
  16063. * objects since the module internally works with Weak Maps
  16064. * for performance reasons.
  16065. *
  16066. * @private
  16067. */
  16068. class ChainMap {
  16069. /**
  16070. * Constructs a new Chain Map.
  16071. */
  16072. constructor() {
  16073. /**
  16074. * The root Weak Map.
  16075. *
  16076. * @type {WeakMap}
  16077. */
  16078. this.weakMap = new WeakMap();
  16079. }
  16080. /**
  16081. * Returns the value for the given array of keys.
  16082. *
  16083. * @param {Array<Object>} keys - List of keys.
  16084. * @return {Any} The value. Returns `undefined` if no value was found.
  16085. */
  16086. get( keys ) {
  16087. let map = this.weakMap;
  16088. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16089. map = map.get( keys[ i ] );
  16090. if ( map === undefined ) return undefined;
  16091. }
  16092. return map.get( keys[ keys.length - 1 ] );
  16093. }
  16094. /**
  16095. * Sets the value for the given keys.
  16096. *
  16097. * @param {Array<Object>} keys - List of keys.
  16098. * @param {Any} value - The value to set.
  16099. * @return {ChainMap} A reference to this Chain Map.
  16100. */
  16101. set( keys, value ) {
  16102. let map = this.weakMap;
  16103. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16104. const key = keys[ i ];
  16105. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  16106. map = map.get( key );
  16107. }
  16108. map.set( keys[ keys.length - 1 ], value );
  16109. return this;
  16110. }
  16111. /**
  16112. * Deletes a value for the given keys.
  16113. *
  16114. * @param {Array<Object>} keys - The keys.
  16115. * @return {Boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  16116. */
  16117. delete( keys ) {
  16118. let map = this.weakMap;
  16119. for ( let i = 0; i < keys.length - 1; i ++ ) {
  16120. map = map.get( keys[ i ] );
  16121. if ( map === undefined ) return false;
  16122. }
  16123. return map.delete( keys[ keys.length - 1 ] );
  16124. }
  16125. }
  16126. let _id$9 = 0;
  16127. function getKeys( obj ) {
  16128. const keys = Object.keys( obj );
  16129. let proto = Object.getPrototypeOf( obj );
  16130. while ( proto ) {
  16131. const descriptors = Object.getOwnPropertyDescriptors( proto );
  16132. for ( const key in descriptors ) {
  16133. if ( descriptors[ key ] !== undefined ) {
  16134. const descriptor = descriptors[ key ];
  16135. if ( descriptor && typeof descriptor.get === 'function' ) {
  16136. keys.push( key );
  16137. }
  16138. }
  16139. }
  16140. proto = Object.getPrototypeOf( proto );
  16141. }
  16142. return keys;
  16143. }
  16144. /**
  16145. * A render object is the renderer's representation of single entity that gets drawn
  16146. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  16147. * scene since render objects also depend from the used material, the current render context
  16148. * and the current scene's lighting.
  16149. *
  16150. * In general, the basic process of the renderer is:
  16151. *
  16152. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  16153. * - Process the render lists by calling one or more render commands for each render item.
  16154. * - For each render command, request a render object and perform the draw.
  16155. *
  16156. * The module provides an interface to get data required for the draw command like the actual
  16157. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  16158. * creating render objects should only be done when necessary.
  16159. *
  16160. * @private
  16161. */
  16162. class RenderObject {
  16163. /**
  16164. * Constructs a new render object.
  16165. *
  16166. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16167. * @param {Geometries} geometries - Renderer component for managing geometries.
  16168. * @param {Renderer} renderer - The renderer.
  16169. * @param {Object3D} object - The 3D object.
  16170. * @param {Material} material - The 3D object's material.
  16171. * @param {Scene} scene - The scene the 3D object belongs to.
  16172. * @param {Camera} camera - The camera the object should be rendered with.
  16173. * @param {LightsNode} lightsNode - The lights node.
  16174. * @param {RenderContext} renderContext - The render context.
  16175. * @param {ClippingContext} clippingContext - The clipping context.
  16176. */
  16177. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  16178. this.id = _id$9 ++;
  16179. /**
  16180. * Renderer component for managing nodes related logic.
  16181. *
  16182. * @type {Nodes}
  16183. * @private
  16184. */
  16185. this._nodes = nodes;
  16186. /**
  16187. * Renderer component for managing geometries.
  16188. *
  16189. * @type {Geometries}
  16190. * @private
  16191. */
  16192. this._geometries = geometries;
  16193. /**
  16194. * The renderer.
  16195. *
  16196. * @type {Renderer}
  16197. */
  16198. this.renderer = renderer;
  16199. /**
  16200. * The 3D object.
  16201. *
  16202. * @type {Object3D}
  16203. */
  16204. this.object = object;
  16205. /**
  16206. * The 3D object's material.
  16207. *
  16208. * @type {Material}
  16209. */
  16210. this.material = material;
  16211. /**
  16212. * The scene the 3D object belongs to.
  16213. *
  16214. * @type {Scene}
  16215. */
  16216. this.scene = scene;
  16217. /**
  16218. * The camera the 3D object should be rendered with.
  16219. *
  16220. * @type {Camera}
  16221. */
  16222. this.camera = camera;
  16223. /**
  16224. * The lights node.
  16225. *
  16226. * @type {LightsNode}
  16227. */
  16228. this.lightsNode = lightsNode;
  16229. /**
  16230. * The render context.
  16231. *
  16232. * @type {RenderContext}
  16233. */
  16234. this.context = renderContext;
  16235. /**
  16236. * The 3D object's geometry.
  16237. *
  16238. * @type {BufferGeometry}
  16239. */
  16240. this.geometry = object.geometry;
  16241. /**
  16242. * The render object's version.
  16243. *
  16244. * @type {Number}
  16245. */
  16246. this.version = material.version;
  16247. /**
  16248. * The draw range of the geometry.
  16249. *
  16250. * @type {Object?}
  16251. * @default null
  16252. */
  16253. this.drawRange = null;
  16254. /**
  16255. * An array holding the buffer attributes
  16256. * of the render object. This entails attribute
  16257. * definitions on geometry and node level.
  16258. *
  16259. * @type {Array<BufferAttribute>?}
  16260. * @default null
  16261. */
  16262. this.attributes = null;
  16263. /**
  16264. * A reference to a render pipeline the render
  16265. * object is processed with.
  16266. *
  16267. * @type {RenderPipeline}
  16268. * @default null
  16269. */
  16270. this.pipeline = null;
  16271. /**
  16272. * Only relevant for objects using
  16273. * multiple materials. This represents a group entry
  16274. * from the respective `BufferGeometry`.
  16275. *
  16276. * @type {{start: Number, count: Number}?}
  16277. * @default null
  16278. */
  16279. this.group = null;
  16280. /**
  16281. * An array holding the vertex buffers which can
  16282. * be buffer attributes but also interleaved buffers.
  16283. *
  16284. * @type {Array<BufferAttribute|InterleavedBuffer>?}
  16285. * @default null
  16286. */
  16287. this.vertexBuffers = null;
  16288. /**
  16289. * The parameters for the draw command.
  16290. *
  16291. * @type {Object?}
  16292. * @default null
  16293. */
  16294. this.drawParams = null;
  16295. /**
  16296. * If this render object is used inside a render bundle,
  16297. * this property points to the respective bundle group.
  16298. *
  16299. * @type {BundleGroup?}
  16300. * @default null
  16301. */
  16302. this.bundle = null;
  16303. /**
  16304. * The clipping context.
  16305. *
  16306. * @type {ClippingContext}
  16307. */
  16308. this.clippingContext = clippingContext;
  16309. /**
  16310. * The clipping context's cache key.
  16311. *
  16312. * @type {String}
  16313. */
  16314. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  16315. /**
  16316. * The initial node cache key.
  16317. *
  16318. * @type {Number}
  16319. */
  16320. this.initialNodesCacheKey = this.getDynamicCacheKey();
  16321. /**
  16322. * The initial cache key.
  16323. *
  16324. * @type {Number}
  16325. */
  16326. this.initialCacheKey = this.getCacheKey();
  16327. /**
  16328. * The node builder state.
  16329. *
  16330. * @type {NodeBuilderState?}
  16331. * @private
  16332. * @default null
  16333. */
  16334. this._nodeBuilderState = null;
  16335. /**
  16336. * An array of bindings.
  16337. *
  16338. * @type {Array<BindGroup>?}
  16339. * @private
  16340. * @default null
  16341. */
  16342. this._bindings = null;
  16343. /**
  16344. * Reference to the node material observer.
  16345. *
  16346. * @type {NodeMaterialObserver?}
  16347. * @private
  16348. * @default null
  16349. */
  16350. this._monitor = null;
  16351. /**
  16352. * An event listener which is defined by `RenderObjects`. It performs
  16353. * clean up tasks when `dispose()` on this render object.
  16354. *
  16355. * @method
  16356. */
  16357. this.onDispose = null;
  16358. /**
  16359. * This flag can be used for type testing.
  16360. *
  16361. * @type {Boolean}
  16362. * @readonly
  16363. * @default true
  16364. */
  16365. this.isRenderObject = true;
  16366. /**
  16367. * An event listener which is executed when `dispose()` is called on
  16368. * the render object's material.
  16369. *
  16370. * @method
  16371. */
  16372. this.onMaterialDispose = () => {
  16373. this.dispose();
  16374. };
  16375. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  16376. }
  16377. /**
  16378. * Updates the clipping context.
  16379. *
  16380. * @param {ClippingContext} context - The clipping context to set.
  16381. */
  16382. updateClipping( context ) {
  16383. this.clippingContext = context;
  16384. }
  16385. /**
  16386. * Whether the clipping requires an update or not.
  16387. *
  16388. * @type {Boolean}
  16389. * @readonly
  16390. */
  16391. get clippingNeedsUpdate() {
  16392. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  16393. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  16394. return true;
  16395. }
  16396. /**
  16397. * The number of clipping planes defined in context of hardware clipping.
  16398. *
  16399. * @type {Number}
  16400. * @readonly
  16401. */
  16402. get hardwareClippingPlanes() {
  16403. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  16404. }
  16405. /**
  16406. * Returns the node builder state of this render object.
  16407. *
  16408. * @return {NodeBuilderState} The node builder state.
  16409. */
  16410. getNodeBuilderState() {
  16411. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  16412. }
  16413. /**
  16414. * Returns the node material observer of this render object.
  16415. *
  16416. * @return {NodeMaterialObserver} The node material observer.
  16417. */
  16418. getMonitor() {
  16419. return this._monitor || ( this._monitor = this.getNodeBuilderState().monitor );
  16420. }
  16421. /**
  16422. * Returns an array of bind groups of this render object.
  16423. *
  16424. * @return {Array<BindGroup>} The bindings.
  16425. */
  16426. getBindings() {
  16427. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  16428. }
  16429. /**
  16430. * Returns a binding group by group name of this render object.
  16431. *
  16432. * @param {String} name - The name of the binding group.
  16433. * @return {BindGroup?} The bindings.
  16434. */
  16435. getBindingGroup( name ) {
  16436. for ( const bindingGroup of this.getBindings() ) {
  16437. if ( bindingGroup.name === name ) {
  16438. return bindingGroup;
  16439. }
  16440. }
  16441. }
  16442. /**
  16443. * Returns the index of the render object's geometry.
  16444. *
  16445. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  16446. */
  16447. getIndex() {
  16448. return this._geometries.getIndex( this );
  16449. }
  16450. /**
  16451. * Returns the indirect buffer attribute.
  16452. *
  16453. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  16454. */
  16455. getIndirect() {
  16456. return this._geometries.getIndirect( this );
  16457. }
  16458. /**
  16459. * Returns an array that acts as a key for identifying the render object in a chain map.
  16460. *
  16461. * @return {Array<Object>} An array with object references.
  16462. */
  16463. getChainArray() {
  16464. return [ this.object, this.material, this.context, this.lightsNode ];
  16465. }
  16466. /**
  16467. * This method is used when the geometry of a 3D object has been exchanged and the
  16468. * respective render object now requires an update.
  16469. *
  16470. * @param {BufferGeometry} geometry - The geometry to set.
  16471. */
  16472. setGeometry( geometry ) {
  16473. this.geometry = geometry;
  16474. this.attributes = null;
  16475. }
  16476. /**
  16477. * Returns the buffer attributes of the render object. The returned array holds
  16478. * attribute definitions on geometry and node level.
  16479. *
  16480. * @return {Array<BufferAttribute>} An array with buffer attributes.
  16481. */
  16482. getAttributes() {
  16483. if ( this.attributes !== null ) return this.attributes;
  16484. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  16485. const geometry = this.geometry;
  16486. const attributes = [];
  16487. const vertexBuffers = new Set();
  16488. for ( const nodeAttribute of nodeAttributes ) {
  16489. const attribute = nodeAttribute.node && nodeAttribute.node.attribute ? nodeAttribute.node.attribute : geometry.getAttribute( nodeAttribute.name );
  16490. if ( attribute === undefined ) continue;
  16491. attributes.push( attribute );
  16492. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  16493. vertexBuffers.add( bufferAttribute );
  16494. }
  16495. this.attributes = attributes;
  16496. this.vertexBuffers = Array.from( vertexBuffers.values() );
  16497. return attributes;
  16498. }
  16499. /**
  16500. * Returns the vertex buffers of the render object.
  16501. *
  16502. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  16503. */
  16504. getVertexBuffers() {
  16505. if ( this.vertexBuffers === null ) this.getAttributes();
  16506. return this.vertexBuffers;
  16507. }
  16508. /**
  16509. * Returns the draw parameters for the render object.
  16510. *
  16511. * @return {{vertexCount: Number, firstVertex: Number, instanceCount: Number, firstInstance: Number}} The draw parameters.
  16512. */
  16513. getDrawParameters() {
  16514. const { object, material, geometry, group, drawRange } = this;
  16515. const drawParams = this.drawParams || ( this.drawParams = {
  16516. vertexCount: 0,
  16517. firstVertex: 0,
  16518. instanceCount: 0,
  16519. firstInstance: 0
  16520. } );
  16521. const index = this.getIndex();
  16522. const hasIndex = ( index !== null );
  16523. const instanceCount = geometry.isInstancedBufferGeometry ? geometry.instanceCount : ( object.count > 1 ? object.count : 1 );
  16524. if ( instanceCount === 0 ) return null;
  16525. drawParams.instanceCount = instanceCount;
  16526. if ( object.isBatchedMesh === true ) return drawParams;
  16527. let rangeFactor = 1;
  16528. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  16529. rangeFactor = 2;
  16530. }
  16531. let firstVertex = drawRange.start * rangeFactor;
  16532. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  16533. if ( group !== null ) {
  16534. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  16535. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  16536. }
  16537. const position = geometry.attributes.position;
  16538. let itemCount = Infinity;
  16539. if ( hasIndex ) {
  16540. itemCount = index.count;
  16541. } else if ( position !== undefined && position !== null ) {
  16542. itemCount = position.count;
  16543. }
  16544. firstVertex = Math.max( firstVertex, 0 );
  16545. lastVertex = Math.min( lastVertex, itemCount );
  16546. const count = lastVertex - firstVertex;
  16547. if ( count < 0 || count === Infinity ) return null;
  16548. drawParams.vertexCount = count;
  16549. drawParams.firstVertex = firstVertex;
  16550. return drawParams;
  16551. }
  16552. /**
  16553. * Returns the render object's geometry cache key.
  16554. *
  16555. * The geometry cache key is part of the material cache key.
  16556. *
  16557. * @return {String} The geometry cache key.
  16558. */
  16559. getGeometryCacheKey() {
  16560. const { geometry } = this;
  16561. let cacheKey = '';
  16562. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  16563. const attribute = geometry.attributes[ name ];
  16564. cacheKey += name + ',';
  16565. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  16566. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  16567. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  16568. if ( attribute.normalized ) cacheKey += 'n,';
  16569. }
  16570. // structural equality isn't sufficient for morph targets since the
  16571. // data are maintained in textures. only if the targets are all equal
  16572. // the texture and thus the instance of `MorphNode` can be shared.
  16573. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  16574. const targets = geometry.morphAttributes[ name ];
  16575. cacheKey += 'morph-' + name + ',';
  16576. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  16577. const attribute = targets[ i ];
  16578. cacheKey += attribute.id + ',';
  16579. }
  16580. }
  16581. if ( geometry.index ) {
  16582. cacheKey += 'index,';
  16583. }
  16584. return cacheKey;
  16585. }
  16586. /**
  16587. * Returns the render object's material cache key.
  16588. *
  16589. * The material cache key is part of the render object cache key.
  16590. *
  16591. * @return {Number} The material cache key.
  16592. */
  16593. getMaterialCacheKey() {
  16594. const { object, material } = this;
  16595. let cacheKey = material.customProgramCacheKey();
  16596. for ( const property of getKeys( material ) ) {
  16597. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  16598. const value = material[ property ];
  16599. let valueKey;
  16600. if ( value !== null ) {
  16601. // some material values require a formatting
  16602. const type = typeof value;
  16603. if ( type === 'number' ) {
  16604. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  16605. } else if ( type === 'object' ) {
  16606. valueKey = '{';
  16607. if ( value.isTexture ) {
  16608. valueKey += value.mapping;
  16609. }
  16610. valueKey += '}';
  16611. } else {
  16612. valueKey = String( value );
  16613. }
  16614. } else {
  16615. valueKey = String( value );
  16616. }
  16617. cacheKey += /*property + ':' +*/ valueKey + ',';
  16618. }
  16619. cacheKey += this.clippingContextCacheKey + ',';
  16620. if ( object.geometry ) {
  16621. cacheKey += this.getGeometryCacheKey();
  16622. }
  16623. if ( object.skeleton ) {
  16624. cacheKey += object.skeleton.bones.length + ',';
  16625. }
  16626. if ( object.isBatchedMesh ) {
  16627. cacheKey += object._matricesTexture.uuid + ',';
  16628. if ( object._colorsTexture !== null ) {
  16629. cacheKey += object._colorsTexture.uuid + ',';
  16630. }
  16631. }
  16632. if ( object.count > 1 ) {
  16633. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  16634. cacheKey += object.uuid + ',';
  16635. }
  16636. cacheKey += object.receiveShadow + ',';
  16637. return hashString( cacheKey );
  16638. }
  16639. /**
  16640. * Whether the geometry requires an update or not.
  16641. *
  16642. * @type {Boolean}
  16643. * @readonly
  16644. */
  16645. get needsGeometryUpdate() {
  16646. return this.geometry.id !== this.object.geometry.id;
  16647. }
  16648. /**
  16649. * Whether the render object requires an update or not.
  16650. *
  16651. * Note: There are two distinct places where render objects are checked for an update.
  16652. *
  16653. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  16654. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  16655. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  16656. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  16657. * a need for a refresh due to material, geometry or object related value changes.
  16658. *
  16659. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  16660. * that performs the 'needsUpdate' check.
  16661. *
  16662. * @type {Boolean}
  16663. * @readonly
  16664. */
  16665. get needsUpdate() {
  16666. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  16667. }
  16668. /**
  16669. * Returns the dynamic cache key which represents a key that is computed per draw command.
  16670. *
  16671. * @return {Number} The cache key.
  16672. */
  16673. getDynamicCacheKey() {
  16674. let cacheKey = 0;
  16675. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  16676. // the renderer is inside a shadow pass.
  16677. if ( this.material.isShadowPassMaterial !== true ) {
  16678. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  16679. }
  16680. if ( this.object.receiveShadow ) {
  16681. cacheKey += 1;
  16682. }
  16683. return cacheKey;
  16684. }
  16685. /**
  16686. * Returns the render object's cache key.
  16687. *
  16688. * @return {Number} The cache key.
  16689. */
  16690. getCacheKey() {
  16691. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  16692. }
  16693. /**
  16694. * Frees internal resources.
  16695. */
  16696. dispose() {
  16697. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  16698. this.onDispose();
  16699. }
  16700. }
  16701. const _chainKeys$5 = [];
  16702. /**
  16703. * This module manages the render objects of the renderer.
  16704. *
  16705. * @private
  16706. */
  16707. class RenderObjects {
  16708. /**
  16709. * Constructs a new render object management component.
  16710. *
  16711. * @param {Renderer} renderer - The renderer.
  16712. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16713. * @param {Geometries} geometries - Renderer component for managing geometries.
  16714. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  16715. * @param {Bindings} bindings - Renderer component for managing bindings.
  16716. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  16717. */
  16718. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  16719. /**
  16720. * The renderer.
  16721. *
  16722. * @type {Renderer}
  16723. */
  16724. this.renderer = renderer;
  16725. /**
  16726. * Renderer component for managing nodes related logic.
  16727. *
  16728. * @type {Nodes}
  16729. */
  16730. this.nodes = nodes;
  16731. /**
  16732. * Renderer component for managing geometries.
  16733. *
  16734. * @type {Geometries}
  16735. */
  16736. this.geometries = geometries;
  16737. /**
  16738. * Renderer component for managing pipelines.
  16739. *
  16740. * @type {Pipelines}
  16741. */
  16742. this.pipelines = pipelines;
  16743. /**
  16744. * Renderer component for managing bindings.
  16745. *
  16746. * @type {Bindings}
  16747. */
  16748. this.bindings = bindings;
  16749. /**
  16750. * Renderer component for managing metrics and monitoring data.
  16751. *
  16752. * @type {Info}
  16753. */
  16754. this.info = info;
  16755. /**
  16756. * A dictionary that manages render contexts in chain maps
  16757. * for each pass ID.
  16758. *
  16759. * @type {Object<String,ChainMap>}
  16760. */
  16761. this.chainMaps = {};
  16762. }
  16763. /**
  16764. * Returns a render object for the given object and state data.
  16765. *
  16766. * @param {Object3D} object - The 3D object.
  16767. * @param {Material} material - The 3D object's material.
  16768. * @param {Scene} scene - The scene the 3D object belongs to.
  16769. * @param {Camera} camera - The camera the 3D object should be rendered with.
  16770. * @param {LightsNode} lightsNode - The lights node.
  16771. * @param {RenderContext} renderContext - The render context.
  16772. * @param {ClippingContext} clippingContext - The clipping context.
  16773. * @param {String?} passId - An optional ID for identifying the pass.
  16774. * @return {RenderObject} The render object.
  16775. */
  16776. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16777. const chainMap = this.getChainMap( passId );
  16778. // reuse chainArray
  16779. _chainKeys$5[ 0 ] = object;
  16780. _chainKeys$5[ 1 ] = material;
  16781. _chainKeys$5[ 2 ] = renderContext;
  16782. _chainKeys$5[ 3 ] = lightsNode;
  16783. let renderObject = chainMap.get( _chainKeys$5 );
  16784. if ( renderObject === undefined ) {
  16785. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16786. chainMap.set( _chainKeys$5, renderObject );
  16787. } else {
  16788. renderObject.updateClipping( clippingContext );
  16789. if ( renderObject.needsGeometryUpdate ) {
  16790. renderObject.setGeometry( object.geometry );
  16791. }
  16792. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  16793. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  16794. renderObject.dispose();
  16795. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  16796. } else {
  16797. renderObject.version = material.version;
  16798. }
  16799. }
  16800. }
  16801. _chainKeys$5.length = 0;
  16802. return renderObject;
  16803. }
  16804. /**
  16805. * Returns a chain map for the given pass ID.
  16806. *
  16807. * @param {String} [passId='default'] - The pass ID.
  16808. * @return {ChainMap} The chain map.
  16809. */
  16810. getChainMap( passId = 'default' ) {
  16811. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  16812. }
  16813. /**
  16814. * Frees internal resources.
  16815. */
  16816. dispose() {
  16817. this.chainMaps = {};
  16818. }
  16819. /**
  16820. * Factory method for creating render objects with the given list of parameters.
  16821. *
  16822. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  16823. * @param {Geometries} geometries - Renderer component for managing geometries.
  16824. * @param {Renderer} renderer - The renderer.
  16825. * @param {Object3D} object - The 3D object.
  16826. * @param {Material} material - The object's material.
  16827. * @param {Scene} scene - The scene the 3D object belongs to.
  16828. * @param {Camera} camera - The camera the object should be rendered with.
  16829. * @param {LightsNode} lightsNode - The lights node.
  16830. * @param {RenderContext} renderContext - The render context.
  16831. * @param {ClippingContext} clippingContext - The clipping context.
  16832. * @param {String?} passId - An optional ID for identifying the pass.
  16833. * @return {RenderObject} The render object.
  16834. */
  16835. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  16836. const chainMap = this.getChainMap( passId );
  16837. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  16838. renderObject.onDispose = () => {
  16839. this.pipelines.delete( renderObject );
  16840. this.bindings.delete( renderObject );
  16841. this.nodes.delete( renderObject );
  16842. chainMap.delete( renderObject.getChainArray() );
  16843. };
  16844. return renderObject;
  16845. }
  16846. }
  16847. /**
  16848. * Data structure for the renderer. It is intended to manage
  16849. * data of objects in dictionaries.
  16850. *
  16851. * @private
  16852. */
  16853. class DataMap {
  16854. /**
  16855. * Constructs a new data map.
  16856. */
  16857. constructor() {
  16858. /**
  16859. * `DataMap` internally uses a weak map
  16860. * to manage its data.
  16861. *
  16862. * @type {WeakMap}
  16863. */
  16864. this.data = new WeakMap();
  16865. }
  16866. /**
  16867. * Returns the dictionary for the given object.
  16868. *
  16869. * @param {Object} object - The object.
  16870. * @return {Object} The dictionary.
  16871. */
  16872. get( object ) {
  16873. let map = this.data.get( object );
  16874. if ( map === undefined ) {
  16875. map = {};
  16876. this.data.set( object, map );
  16877. }
  16878. return map;
  16879. }
  16880. /**
  16881. * Deletes the dictionary for the given object.
  16882. *
  16883. * @param {Object} object - The object.
  16884. * @return {Object?} The deleted dictionary.
  16885. */
  16886. delete( object ) {
  16887. let map = null;
  16888. if ( this.data.has( object ) ) {
  16889. map = this.data.get( object );
  16890. this.data.delete( object );
  16891. }
  16892. return map;
  16893. }
  16894. /**
  16895. * Returns `true` if the given object has a dictionary defined.
  16896. *
  16897. * @param {Object} object - The object to test.
  16898. * @return {Boolean} Whether a dictionary is defined or not.
  16899. */
  16900. has( object ) {
  16901. return this.data.has( object );
  16902. }
  16903. /**
  16904. * Frees internal resources.
  16905. */
  16906. dispose() {
  16907. this.data = new WeakMap();
  16908. }
  16909. }
  16910. const AttributeType = {
  16911. VERTEX: 1,
  16912. INDEX: 2,
  16913. STORAGE: 3,
  16914. INDIRECT: 4
  16915. };
  16916. // size of a chunk in bytes (STD140 layout)
  16917. const GPU_CHUNK_BYTES = 16;
  16918. // @TODO: Move to src/constants.js
  16919. const BlendColorFactor = 211;
  16920. const OneMinusBlendColorFactor = 212;
  16921. /**
  16922. * This renderer module manages geometry attributes.
  16923. *
  16924. * @private
  16925. * @augments DataMap
  16926. */
  16927. class Attributes extends DataMap {
  16928. /**
  16929. * Constructs a new attribute management component.
  16930. *
  16931. * @param {Backend} backend - The renderer's backend.
  16932. */
  16933. constructor( backend ) {
  16934. super();
  16935. /**
  16936. * The renderer's backend.
  16937. *
  16938. * @type {Backend}
  16939. */
  16940. this.backend = backend;
  16941. }
  16942. /**
  16943. * Deletes the data for the given attribute.
  16944. *
  16945. * @param {BufferAttribute} attribute - The attribute.
  16946. * @return {Object} The deleted attribute data.
  16947. */
  16948. delete( attribute ) {
  16949. const attributeData = super.delete( attribute );
  16950. if ( attributeData !== undefined ) {
  16951. this.backend.destroyAttribute( attribute );
  16952. }
  16953. return attributeData;
  16954. }
  16955. /**
  16956. * Updates the given attribute. This method creates attribute buffers
  16957. * for new attributes and updates data for existing ones.
  16958. *
  16959. * @param {BufferAttribute} attribute - The attribute to update.
  16960. * @param {Number} type - The attribute type.
  16961. */
  16962. update( attribute, type ) {
  16963. const data = this.get( attribute );
  16964. if ( data.version === undefined ) {
  16965. if ( type === AttributeType.VERTEX ) {
  16966. this.backend.createAttribute( attribute );
  16967. } else if ( type === AttributeType.INDEX ) {
  16968. this.backend.createIndexAttribute( attribute );
  16969. } else if ( type === AttributeType.STORAGE ) {
  16970. this.backend.createStorageAttribute( attribute );
  16971. } else if ( type === AttributeType.INDIRECT ) {
  16972. this.backend.createIndirectStorageAttribute( attribute );
  16973. }
  16974. data.version = this._getBufferAttribute( attribute ).version;
  16975. } else {
  16976. const bufferAttribute = this._getBufferAttribute( attribute );
  16977. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  16978. this.backend.updateAttribute( attribute );
  16979. data.version = bufferAttribute.version;
  16980. }
  16981. }
  16982. }
  16983. /**
  16984. * Utility method for handling interleaved buffer attributes correctly.
  16985. * To process them, their `InterleavedBuffer` is returned.
  16986. *
  16987. * @param {BufferAttribute} attribute - The attribute.
  16988. * @return {BufferAttribute|InterleavedBuffer}
  16989. */
  16990. _getBufferAttribute( attribute ) {
  16991. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  16992. return attribute;
  16993. }
  16994. }
  16995. /**
  16996. * Returns `true` if the given array has values that require an Uint32 array type.
  16997. *
  16998. * @private
  16999. * @function
  17000. * @param {Array<Number>} array - The array to test.
  17001. * @return {Boolean} Whether the given array has values that require an Uint32 array type or not.
  17002. */
  17003. function arrayNeedsUint32( array ) {
  17004. // assumes larger values usually on last
  17005. for ( let i = array.length - 1; i >= 0; -- i ) {
  17006. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  17007. }
  17008. return false;
  17009. }
  17010. /**
  17011. * Returns the wireframe version for the given geometry.
  17012. *
  17013. * @private
  17014. * @function
  17015. * @param {BufferGeometry} geometry - The geometry.
  17016. * @return {Number} The version.
  17017. */
  17018. function getWireframeVersion( geometry ) {
  17019. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  17020. }
  17021. /**
  17022. * Returns a wireframe index attribute for the given geometry.
  17023. *
  17024. * @private
  17025. * @function
  17026. * @param {BufferGeometry} geometry - The geometry.
  17027. * @return {BufferAttribute} The wireframe index attribute.
  17028. */
  17029. function getWireframeIndex( geometry ) {
  17030. const indices = [];
  17031. const geometryIndex = geometry.index;
  17032. const geometryPosition = geometry.attributes.position;
  17033. if ( geometryIndex !== null ) {
  17034. const array = geometryIndex.array;
  17035. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  17036. const a = array[ i + 0 ];
  17037. const b = array[ i + 1 ];
  17038. const c = array[ i + 2 ];
  17039. indices.push( a, b, b, c, c, a );
  17040. }
  17041. } else {
  17042. const array = geometryPosition.array;
  17043. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  17044. const a = i + 0;
  17045. const b = i + 1;
  17046. const c = i + 2;
  17047. indices.push( a, b, b, c, c, a );
  17048. }
  17049. }
  17050. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  17051. attribute.version = getWireframeVersion( geometry );
  17052. return attribute;
  17053. }
  17054. /**
  17055. * This renderer module manages geometries.
  17056. *
  17057. * @private
  17058. * @augments DataMap
  17059. */
  17060. class Geometries extends DataMap {
  17061. /**
  17062. * Constructs a new geometry management component.
  17063. *
  17064. * @param {Attributes} attributes - Renderer component for managing attributes.
  17065. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17066. */
  17067. constructor( attributes, info ) {
  17068. super();
  17069. /**
  17070. * Renderer component for managing attributes.
  17071. *
  17072. * @type {Attributes}
  17073. */
  17074. this.attributes = attributes;
  17075. /**
  17076. * Renderer component for managing metrics and monitoring data.
  17077. *
  17078. * @type {Info}
  17079. */
  17080. this.info = info;
  17081. /**
  17082. * Weak Map for managing attributes for wireframe rendering.
  17083. *
  17084. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  17085. */
  17086. this.wireframes = new WeakMap();
  17087. /**
  17088. * This Weak Map is used to make sure buffer attributes are
  17089. * updated only once per render call.
  17090. *
  17091. * @type {WeakMap<BufferAttribute,Number>}
  17092. */
  17093. this.attributeCall = new WeakMap();
  17094. }
  17095. /**
  17096. * Returns `true` if the given render object has an initialized geometry.
  17097. *
  17098. * @param {RenderObject} renderObject - The render object.
  17099. * @return {Boolean} Whether if the given render object has an initialized geometry or not.
  17100. */
  17101. has( renderObject ) {
  17102. const geometry = renderObject.geometry;
  17103. return super.has( geometry ) && this.get( geometry ).initialized === true;
  17104. }
  17105. /**
  17106. * Prepares the geometry of the given render object for rendering.
  17107. *
  17108. * @param {RenderObject} renderObject - The render object.
  17109. */
  17110. updateForRender( renderObject ) {
  17111. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  17112. this.updateAttributes( renderObject );
  17113. }
  17114. /**
  17115. * Initializes the geometry of the given render object.
  17116. *
  17117. * @param {RenderObject} renderObject - The render object.
  17118. */
  17119. initGeometry( renderObject ) {
  17120. const geometry = renderObject.geometry;
  17121. const geometryData = this.get( geometry );
  17122. geometryData.initialized = true;
  17123. this.info.memory.geometries ++;
  17124. const onDispose = () => {
  17125. this.info.memory.geometries --;
  17126. const index = geometry.index;
  17127. const geometryAttributes = renderObject.getAttributes();
  17128. if ( index !== null ) {
  17129. this.attributes.delete( index );
  17130. }
  17131. for ( const geometryAttribute of geometryAttributes ) {
  17132. this.attributes.delete( geometryAttribute );
  17133. }
  17134. const wireframeAttribute = this.wireframes.get( geometry );
  17135. if ( wireframeAttribute !== undefined ) {
  17136. this.attributes.delete( wireframeAttribute );
  17137. }
  17138. geometry.removeEventListener( 'dispose', onDispose );
  17139. };
  17140. geometry.addEventListener( 'dispose', onDispose );
  17141. }
  17142. /**
  17143. * Updates the geometry attributes of the given render object.
  17144. *
  17145. * @param {RenderObject} renderObject - The render object.
  17146. */
  17147. updateAttributes( renderObject ) {
  17148. // attributes
  17149. const attributes = renderObject.getAttributes();
  17150. for ( const attribute of attributes ) {
  17151. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  17152. this.updateAttribute( attribute, AttributeType.STORAGE );
  17153. } else {
  17154. this.updateAttribute( attribute, AttributeType.VERTEX );
  17155. }
  17156. }
  17157. // indexes
  17158. const index = this.getIndex( renderObject );
  17159. if ( index !== null ) {
  17160. this.updateAttribute( index, AttributeType.INDEX );
  17161. }
  17162. // indirect
  17163. const indirect = renderObject.geometry.indirect;
  17164. if ( indirect !== null ) {
  17165. this.updateAttribute( indirect, AttributeType.INDIRECT );
  17166. }
  17167. }
  17168. /**
  17169. * Updates the given attribute.
  17170. *
  17171. * @param {BufferAttribute} attribute - The attribute to update.
  17172. * @param {Number} type - The attribute type.
  17173. */
  17174. updateAttribute( attribute, type ) {
  17175. const callId = this.info.render.calls;
  17176. if ( ! attribute.isInterleavedBufferAttribute ) {
  17177. if ( this.attributeCall.get( attribute ) !== callId ) {
  17178. this.attributes.update( attribute, type );
  17179. this.attributeCall.set( attribute, callId );
  17180. }
  17181. } else {
  17182. if ( this.attributeCall.get( attribute ) === undefined ) {
  17183. this.attributes.update( attribute, type );
  17184. this.attributeCall.set( attribute, callId );
  17185. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  17186. this.attributes.update( attribute, type );
  17187. this.attributeCall.set( attribute.data, callId );
  17188. this.attributeCall.set( attribute, callId );
  17189. }
  17190. }
  17191. }
  17192. /**
  17193. * Returns the indirect buffer attribute of the given render object.
  17194. *
  17195. * @param {RenderObject} renderObject - The render object.
  17196. * @return {BufferAttribute?} The indirect attribute. `null` if no indirect drawing is used.
  17197. */
  17198. getIndirect( renderObject ) {
  17199. return renderObject.geometry.indirect;
  17200. }
  17201. /**
  17202. * Returns the index of the given render object's geometry. This is implemented
  17203. * in a method to return a wireframe index if necessary.
  17204. *
  17205. * @param {RenderObject} renderObject - The render object.
  17206. * @return {BufferAttribute?} The index. Returns `null` for non-indexed geometries.
  17207. */
  17208. getIndex( renderObject ) {
  17209. const { geometry, material } = renderObject;
  17210. let index = geometry.index;
  17211. if ( material.wireframe === true ) {
  17212. const wireframes = this.wireframes;
  17213. let wireframeAttribute = wireframes.get( geometry );
  17214. if ( wireframeAttribute === undefined ) {
  17215. wireframeAttribute = getWireframeIndex( geometry );
  17216. wireframes.set( geometry, wireframeAttribute );
  17217. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  17218. this.attributes.delete( wireframeAttribute );
  17219. wireframeAttribute = getWireframeIndex( geometry );
  17220. wireframes.set( geometry, wireframeAttribute );
  17221. }
  17222. index = wireframeAttribute;
  17223. }
  17224. return index;
  17225. }
  17226. }
  17227. /**
  17228. * This renderer module provides a series of statistical information
  17229. * about the GPU memory and the rendering process. Useful for debugging
  17230. * and monitoring.
  17231. */
  17232. class Info {
  17233. /**
  17234. * Constructs a new info component.
  17235. */
  17236. constructor() {
  17237. /**
  17238. * Whether frame related metrics should automatically
  17239. * be resetted or not. This property should be set to `false`
  17240. * by apps which manage their own animation loop. They must
  17241. * then call `renderer.info.reset()` once per frame manually.
  17242. *
  17243. * @type {Boolean}
  17244. * @default true
  17245. */
  17246. this.autoReset = true;
  17247. /**
  17248. * The current frame ID. This ID is managed
  17249. * by `NodeFrame`.
  17250. *
  17251. * @type {Number}
  17252. * @readonly
  17253. * @default 0
  17254. */
  17255. this.frame = 0;
  17256. /**
  17257. * The number of render calls since the
  17258. * app has been started.
  17259. *
  17260. * @type {Number}
  17261. * @readonly
  17262. * @default 0
  17263. */
  17264. this.calls = 0;
  17265. /**
  17266. * Render related metrics.
  17267. *
  17268. * @type {Object}
  17269. * @readonly
  17270. * @property {Number} calls - The number of render calls since the app has been started.
  17271. * @property {Number} frameCalls - The number of render calls of the current frame.
  17272. * @property {Number} drawCalls - The number of draw calls of the current frame.
  17273. * @property {Number} triangles - The number of rendered triangle primitives of the current frame.
  17274. * @property {Number} points - The number of rendered point primitives of the current frame.
  17275. * @property {Number} lines - The number of rendered line primitives of the current frame.
  17276. * @property {Number} previousFrameCalls - The number of render calls of the previous frame.
  17277. * @property {Number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  17278. * @property {Number} timestampCalls - The number of render calls using `renderer.renderAsync()`.
  17279. */
  17280. this.render = {
  17281. calls: 0,
  17282. frameCalls: 0,
  17283. drawCalls: 0,
  17284. triangles: 0,
  17285. points: 0,
  17286. lines: 0,
  17287. timestamp: 0,
  17288. previousFrameCalls: 0,
  17289. timestampCalls: 0
  17290. };
  17291. /**
  17292. * Compute related metrics.
  17293. *
  17294. * @type {Object}
  17295. * @readonly
  17296. * @property {Number} calls - The number of compute calls since the app has been started.
  17297. * @property {Number} frameCalls - The number of compute calls of the current frame.
  17298. * @property {Number} previousFrameCalls - The number of compute calls of the previous frame.
  17299. * @property {Number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  17300. * @property {Number} timestampCalls - The number of render calls using `renderer.computeAsync()`.
  17301. */
  17302. this.compute = {
  17303. calls: 0,
  17304. frameCalls: 0,
  17305. timestamp: 0,
  17306. previousFrameCalls: 0,
  17307. timestampCalls: 0
  17308. };
  17309. /**
  17310. * Memory related metrics.
  17311. *
  17312. * @type {Object}
  17313. * @readonly
  17314. * @property {Number} geometries - The number of active geometries.
  17315. * @property {Number} frameCalls - The number of active textures.
  17316. */
  17317. this.memory = {
  17318. geometries: 0,
  17319. textures: 0
  17320. };
  17321. }
  17322. /**
  17323. * This method should be executed per draw call and updates the corresponding metrics.
  17324. *
  17325. * @param {Object3D} object - The 3D object that is going to be rendered.
  17326. * @param {Number} count - The vertex or index count.
  17327. * @param {Number} instanceCount - The instance count.
  17328. */
  17329. update( object, count, instanceCount ) {
  17330. this.render.drawCalls ++;
  17331. if ( object.isMesh || object.isSprite ) {
  17332. this.render.triangles += instanceCount * ( count / 3 );
  17333. } else if ( object.isPoints ) {
  17334. this.render.points += instanceCount * count;
  17335. } else if ( object.isLineSegments ) {
  17336. this.render.lines += instanceCount * ( count / 2 );
  17337. } else if ( object.isLine ) {
  17338. this.render.lines += instanceCount * ( count - 1 );
  17339. } else {
  17340. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  17341. }
  17342. }
  17343. /**
  17344. * Used by async render methods to updated timestamp metrics.
  17345. *
  17346. * @param {('render'|'compute')} type - The type of render call.
  17347. * @param {Number} time - The duration of the compute/render call in milliseconds.
  17348. */
  17349. updateTimestamp( type, time ) {
  17350. if ( this[ type ].timestampCalls === 0 ) {
  17351. this[ type ].timestamp = 0;
  17352. }
  17353. this[ type ].timestamp += time;
  17354. this[ type ].timestampCalls ++;
  17355. if ( this[ type ].timestampCalls >= this[ type ].previousFrameCalls ) {
  17356. this[ type ].timestampCalls = 0;
  17357. }
  17358. }
  17359. /**
  17360. * Resets frame related metrics.
  17361. */
  17362. reset() {
  17363. const previousRenderFrameCalls = this.render.frameCalls;
  17364. this.render.previousFrameCalls = previousRenderFrameCalls;
  17365. const previousComputeFrameCalls = this.compute.frameCalls;
  17366. this.compute.previousFrameCalls = previousComputeFrameCalls;
  17367. this.render.drawCalls = 0;
  17368. this.render.frameCalls = 0;
  17369. this.compute.frameCalls = 0;
  17370. this.render.triangles = 0;
  17371. this.render.points = 0;
  17372. this.render.lines = 0;
  17373. }
  17374. /**
  17375. * Performs a complete reset of the object.
  17376. */
  17377. dispose() {
  17378. this.reset();
  17379. this.calls = 0;
  17380. this.render.calls = 0;
  17381. this.compute.calls = 0;
  17382. this.render.timestamp = 0;
  17383. this.compute.timestamp = 0;
  17384. this.memory.geometries = 0;
  17385. this.memory.textures = 0;
  17386. }
  17387. }
  17388. /**
  17389. * Abstract class for representing pipelines.
  17390. *
  17391. * @private
  17392. * @abstract
  17393. */
  17394. class Pipeline {
  17395. /**
  17396. * Constructs a new pipeline.
  17397. *
  17398. * @param {String} cacheKey - The pipeline's cache key.
  17399. */
  17400. constructor( cacheKey ) {
  17401. /**
  17402. * The pipeline's cache key.
  17403. *
  17404. * @type {String}
  17405. */
  17406. this.cacheKey = cacheKey;
  17407. /**
  17408. * How often the pipeline is currently in use.
  17409. *
  17410. * @type {Number}
  17411. * @default 0
  17412. */
  17413. this.usedTimes = 0;
  17414. }
  17415. }
  17416. /**
  17417. * Class for representing render pipelines.
  17418. *
  17419. * @private
  17420. * @augments Pipeline
  17421. */
  17422. class RenderPipeline extends Pipeline {
  17423. /**
  17424. * Constructs a new render pipeline.
  17425. *
  17426. * @param {String} cacheKey - The pipeline's cache key.
  17427. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  17428. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  17429. */
  17430. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  17431. super( cacheKey );
  17432. /**
  17433. * The pipeline's vertex shader.
  17434. *
  17435. * @type {ProgrammableStage}
  17436. */
  17437. this.vertexProgram = vertexProgram;
  17438. /**
  17439. * The pipeline's fragment shader.
  17440. *
  17441. * @type {ProgrammableStage}
  17442. */
  17443. this.fragmentProgram = fragmentProgram;
  17444. }
  17445. }
  17446. /**
  17447. * Class for representing compute pipelines.
  17448. *
  17449. * @private
  17450. * @augments Pipeline
  17451. */
  17452. class ComputePipeline extends Pipeline {
  17453. /**
  17454. * Constructs a new render pipeline.
  17455. *
  17456. * @param {String} cacheKey - The pipeline's cache key.
  17457. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  17458. */
  17459. constructor( cacheKey, computeProgram ) {
  17460. super( cacheKey );
  17461. /**
  17462. * The pipeline's compute shader.
  17463. *
  17464. * @type {ProgrammableStage}
  17465. */
  17466. this.computeProgram = computeProgram;
  17467. /**
  17468. * This flag can be used for type testing.
  17469. *
  17470. * @type {Boolean}
  17471. * @readonly
  17472. * @default true
  17473. */
  17474. this.isComputePipeline = true;
  17475. }
  17476. }
  17477. let _id$8 = 0;
  17478. /**
  17479. * Class for representing programmable stages which are vertex,
  17480. * fragment or compute shaders. Unlike fixed-function states (like blending),
  17481. * they represent the programmable part of a pipeline.
  17482. *
  17483. * @private
  17484. */
  17485. class ProgrammableStage {
  17486. /**
  17487. * Constructs a new programmable stage.
  17488. *
  17489. * @param {String} code - The shader code.
  17490. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  17491. * @param {String} name - The name of the shader.
  17492. * @param {Array<Object>?} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17493. * @param {Array<Object>?} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17494. */
  17495. constructor( code, stage, name, transforms = null, attributes = null ) {
  17496. /**
  17497. * The id of the programmable stage.
  17498. *
  17499. * @type {Number}
  17500. */
  17501. this.id = _id$8 ++;
  17502. /**
  17503. * The shader code.
  17504. *
  17505. * @type {String}
  17506. */
  17507. this.code = code;
  17508. /**
  17509. * The type of stage.
  17510. *
  17511. * @type {String}
  17512. */
  17513. this.stage = stage;
  17514. /**
  17515. * The name of the stage.
  17516. * This is used for debugging purposes.
  17517. *
  17518. * @type {String}
  17519. */
  17520. this.name = name;
  17521. /**
  17522. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17523. *
  17524. * @type {Array<Object>?}
  17525. */
  17526. this.transforms = transforms;
  17527. /**
  17528. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  17529. *
  17530. * @type {Array<Object>?}
  17531. */
  17532. this.attributes = attributes;
  17533. /**
  17534. * How often the programmable stage is currently in use.
  17535. *
  17536. * @type {Number}
  17537. * @default 0
  17538. */
  17539. this.usedTimes = 0;
  17540. }
  17541. }
  17542. /**
  17543. * This renderer module manages the pipelines of the renderer.
  17544. *
  17545. * @private
  17546. * @augments DataMap
  17547. */
  17548. class Pipelines extends DataMap {
  17549. /**
  17550. * Constructs a new pipeline management component.
  17551. *
  17552. * @param {Backend} backend - The renderer's backend.
  17553. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17554. */
  17555. constructor( backend, nodes ) {
  17556. super();
  17557. /**
  17558. * The renderer's backend.
  17559. *
  17560. * @type {Backend}
  17561. */
  17562. this.backend = backend;
  17563. /**
  17564. * Renderer component for managing nodes related logic.
  17565. *
  17566. * @type {Nodes}
  17567. */
  17568. this.nodes = nodes;
  17569. /**
  17570. * A references to the bindings management component.
  17571. * This reference will be set inside the `Bindings`
  17572. * constructor.
  17573. *
  17574. * @type {Bindings?}
  17575. * @default null
  17576. */
  17577. this.bindings = null;
  17578. /**
  17579. * Internal cache for maintaining pipelines.
  17580. * The key of the map is a cache key, the value the pipeline.
  17581. *
  17582. * @type {Map<String,Pipeline>}
  17583. */
  17584. this.caches = new Map();
  17585. /**
  17586. * This dictionary maintains for each shader stage type (vertex,
  17587. * fragment and compute) the programmable stage objects which
  17588. * represent the actual shader code.
  17589. *
  17590. * @type {Object<String,Map>}
  17591. */
  17592. this.programs = {
  17593. vertex: new Map(),
  17594. fragment: new Map(),
  17595. compute: new Map()
  17596. };
  17597. }
  17598. /**
  17599. * Returns a compute pipeline for the given compute node.
  17600. *
  17601. * @param {Node} computeNode - The compute node.
  17602. * @param {Array<BindGroup>} bindings - The bindings.
  17603. * @return {ComputePipeline} The compute pipeline.
  17604. */
  17605. getForCompute( computeNode, bindings ) {
  17606. const { backend } = this;
  17607. const data = this.get( computeNode );
  17608. if ( this._needsComputeUpdate( computeNode ) ) {
  17609. const previousPipeline = data.pipeline;
  17610. if ( previousPipeline ) {
  17611. previousPipeline.usedTimes --;
  17612. previousPipeline.computeProgram.usedTimes --;
  17613. }
  17614. // get shader
  17615. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  17616. // programmable stage
  17617. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  17618. if ( stageCompute === undefined ) {
  17619. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  17620. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  17621. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  17622. backend.createProgram( stageCompute );
  17623. }
  17624. // determine compute pipeline
  17625. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  17626. let pipeline = this.caches.get( cacheKey );
  17627. if ( pipeline === undefined ) {
  17628. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17629. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  17630. }
  17631. // keep track of all used times
  17632. pipeline.usedTimes ++;
  17633. stageCompute.usedTimes ++;
  17634. //
  17635. data.version = computeNode.version;
  17636. data.pipeline = pipeline;
  17637. }
  17638. return data.pipeline;
  17639. }
  17640. /**
  17641. * Returns a render pipeline for the given render object.
  17642. *
  17643. * @param {RenderObject} renderObject - The render object.
  17644. * @param {Array<Promise>?} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17645. * @return {RenderPipeline} The render pipeline.
  17646. */
  17647. getForRender( renderObject, promises = null ) {
  17648. const { backend } = this;
  17649. const data = this.get( renderObject );
  17650. if ( this._needsRenderUpdate( renderObject ) ) {
  17651. const previousPipeline = data.pipeline;
  17652. if ( previousPipeline ) {
  17653. previousPipeline.usedTimes --;
  17654. previousPipeline.vertexProgram.usedTimes --;
  17655. previousPipeline.fragmentProgram.usedTimes --;
  17656. }
  17657. // get shader
  17658. const nodeBuilderState = renderObject.getNodeBuilderState();
  17659. const name = renderObject.material ? renderObject.material.name : '';
  17660. // programmable stages
  17661. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  17662. if ( stageVertex === undefined ) {
  17663. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  17664. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  17665. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  17666. backend.createProgram( stageVertex );
  17667. }
  17668. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  17669. if ( stageFragment === undefined ) {
  17670. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  17671. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  17672. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  17673. backend.createProgram( stageFragment );
  17674. }
  17675. // determine render pipeline
  17676. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17677. let pipeline = this.caches.get( cacheKey );
  17678. if ( pipeline === undefined ) {
  17679. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  17680. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  17681. } else {
  17682. renderObject.pipeline = pipeline;
  17683. }
  17684. // keep track of all used times
  17685. pipeline.usedTimes ++;
  17686. stageVertex.usedTimes ++;
  17687. stageFragment.usedTimes ++;
  17688. //
  17689. data.pipeline = pipeline;
  17690. }
  17691. return data.pipeline;
  17692. }
  17693. /**
  17694. * Deletes the pipeline for the given render object.
  17695. *
  17696. * @param {RenderObject} object - The render object.
  17697. * @return {Object?} The deleted dictionary.
  17698. */
  17699. delete( object ) {
  17700. const pipeline = this.get( object ).pipeline;
  17701. if ( pipeline ) {
  17702. // pipeline
  17703. pipeline.usedTimes --;
  17704. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  17705. // programs
  17706. if ( pipeline.isComputePipeline ) {
  17707. pipeline.computeProgram.usedTimes --;
  17708. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  17709. } else {
  17710. pipeline.fragmentProgram.usedTimes --;
  17711. pipeline.vertexProgram.usedTimes --;
  17712. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  17713. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  17714. }
  17715. }
  17716. return super.delete( object );
  17717. }
  17718. /**
  17719. * Frees internal resources.
  17720. */
  17721. dispose() {
  17722. super.dispose();
  17723. this.caches = new Map();
  17724. this.programs = {
  17725. vertex: new Map(),
  17726. fragment: new Map(),
  17727. compute: new Map()
  17728. };
  17729. }
  17730. /**
  17731. * Updates the pipeline for the given render object.
  17732. *
  17733. * @param {RenderObject} renderObject - The render object.
  17734. */
  17735. updateForRender( renderObject ) {
  17736. this.getForRender( renderObject );
  17737. }
  17738. /**
  17739. * Returns a compute pipeline for the given parameters.
  17740. *
  17741. * @private
  17742. * @param {Node} computeNode - The compute node.
  17743. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17744. * @param {String} cacheKey - The cache key.
  17745. * @param {Array<BindGroup>} bindings - The bindings.
  17746. * @return {ComputePipeline} The compute pipeline.
  17747. */
  17748. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  17749. // check for existing pipeline
  17750. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  17751. let pipeline = this.caches.get( cacheKey );
  17752. if ( pipeline === undefined ) {
  17753. pipeline = new ComputePipeline( cacheKey, stageCompute );
  17754. this.caches.set( cacheKey, pipeline );
  17755. this.backend.createComputePipeline( pipeline, bindings );
  17756. }
  17757. return pipeline;
  17758. }
  17759. /**
  17760. * Returns a render pipeline for the given parameters.
  17761. *
  17762. * @private
  17763. * @param {RenderObject} renderObject - The render object.
  17764. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17765. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17766. * @param {String} cacheKey - The cache key.
  17767. * @param {Array<Promise>?} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  17768. * @return {ComputePipeline} The compute pipeline.
  17769. */
  17770. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  17771. // check for existing pipeline
  17772. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  17773. let pipeline = this.caches.get( cacheKey );
  17774. if ( pipeline === undefined ) {
  17775. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  17776. this.caches.set( cacheKey, pipeline );
  17777. renderObject.pipeline = pipeline;
  17778. // The `promises` array is `null` by default and only set to an empty array when
  17779. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  17780. // pending promises that resolve when the render pipelines are ready for rendering.
  17781. this.backend.createRenderPipeline( renderObject, promises );
  17782. }
  17783. return pipeline;
  17784. }
  17785. /**
  17786. * Computes a cache key representing a compute pipeline.
  17787. *
  17788. * @private
  17789. * @param {Node} computeNode - The compute node.
  17790. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  17791. * @return {String} The cache key.
  17792. */
  17793. _getComputeCacheKey( computeNode, stageCompute ) {
  17794. return computeNode.id + ',' + stageCompute.id;
  17795. }
  17796. /**
  17797. * Computes a cache key representing a render pipeline.
  17798. *
  17799. * @private
  17800. * @param {RenderObject} renderObject - The render object.
  17801. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  17802. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  17803. * @return {String} The cache key.
  17804. */
  17805. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  17806. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  17807. }
  17808. /**
  17809. * Releases the given pipeline.
  17810. *
  17811. * @private
  17812. * @param {Pipeline} pipeline - The pipeline to release.
  17813. */
  17814. _releasePipeline( pipeline ) {
  17815. this.caches.delete( pipeline.cacheKey );
  17816. }
  17817. /**
  17818. * Releases the shader program.
  17819. *
  17820. * @private
  17821. * @param {Object} program - The shader program to release.
  17822. */
  17823. _releaseProgram( program ) {
  17824. const code = program.code;
  17825. const stage = program.stage;
  17826. this.programs[ stage ].delete( code );
  17827. }
  17828. /**
  17829. * Returns `true` if the compute pipeline for the given compute node requires an update.
  17830. *
  17831. * @private
  17832. * @param {Node} computeNode - The compute node.
  17833. * @return {Boolean} Whether the compute pipeline for the given compute node requires an update or not.
  17834. */
  17835. _needsComputeUpdate( computeNode ) {
  17836. const data = this.get( computeNode );
  17837. return data.pipeline === undefined || data.version !== computeNode.version;
  17838. }
  17839. /**
  17840. * Returns `true` if the render pipeline for the given render object requires an update.
  17841. *
  17842. * @private
  17843. * @param {RenderObject} renderObject - The render object.
  17844. * @return {Boolean} Whether the render object for the given render object requires an update or not.
  17845. */
  17846. _needsRenderUpdate( renderObject ) {
  17847. const data = this.get( renderObject );
  17848. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  17849. }
  17850. }
  17851. /**
  17852. * This renderer module manages the bindings of the renderer.
  17853. *
  17854. * @private
  17855. * @augments DataMap
  17856. */
  17857. class Bindings extends DataMap {
  17858. /**
  17859. * Constructs a new bindings management component.
  17860. *
  17861. * @param {Backend} backend - The renderer's backend.
  17862. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  17863. * @param {Textures} textures - Renderer component for managing textures.
  17864. * @param {Attributes} attributes - Renderer component for managing attributes.
  17865. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  17866. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  17867. */
  17868. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  17869. super();
  17870. /**
  17871. * The renderer's backend.
  17872. *
  17873. * @type {Backend}
  17874. */
  17875. this.backend = backend;
  17876. /**
  17877. * Renderer component for managing textures.
  17878. *
  17879. * @type {Textures}
  17880. */
  17881. this.textures = textures;
  17882. /**
  17883. * Renderer component for managing pipelines.
  17884. *
  17885. * @type {Pipelines}
  17886. */
  17887. this.pipelines = pipelines;
  17888. /**
  17889. * Renderer component for managing attributes.
  17890. *
  17891. * @type {Attributes}
  17892. */
  17893. this.attributes = attributes;
  17894. /**
  17895. * Renderer component for managing nodes related logic.
  17896. *
  17897. * @type {Nodes}
  17898. */
  17899. this.nodes = nodes;
  17900. /**
  17901. * Renderer component for managing metrics and monitoring data.
  17902. *
  17903. * @type {Info}
  17904. */
  17905. this.info = info;
  17906. this.pipelines.bindings = this; // assign bindings to pipelines
  17907. }
  17908. /**
  17909. * Returns the bind groups for the given render object.
  17910. *
  17911. * @param {RenderObject} renderObject - The render object.
  17912. * @return {Array<BindGroup>} The bind groups.
  17913. */
  17914. getForRender( renderObject ) {
  17915. const bindings = renderObject.getBindings();
  17916. for ( const bindGroup of bindings ) {
  17917. const groupData = this.get( bindGroup );
  17918. if ( groupData.bindGroup === undefined ) {
  17919. // each object defines an array of bindings (ubos, textures, samplers etc.)
  17920. this._init( bindGroup );
  17921. this.backend.createBindings( bindGroup, bindings, 0 );
  17922. groupData.bindGroup = bindGroup;
  17923. }
  17924. }
  17925. return bindings;
  17926. }
  17927. /**
  17928. * Returns the bind groups for the given compute node.
  17929. *
  17930. * @param {Node} computeNode - The compute node.
  17931. * @return {Array<BindGroup>} The bind groups.
  17932. */
  17933. getForCompute( computeNode ) {
  17934. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  17935. for ( const bindGroup of bindings ) {
  17936. const groupData = this.get( bindGroup );
  17937. if ( groupData.bindGroup === undefined ) {
  17938. this._init( bindGroup );
  17939. this.backend.createBindings( bindGroup, bindings, 0 );
  17940. groupData.bindGroup = bindGroup;
  17941. }
  17942. }
  17943. return bindings;
  17944. }
  17945. /**
  17946. * Updates the bindings for the given compute node.
  17947. *
  17948. * @param {Node} computeNode - The compute node.
  17949. */
  17950. updateForCompute( computeNode ) {
  17951. this._updateBindings( this.getForCompute( computeNode ) );
  17952. }
  17953. /**
  17954. * Updates the bindings for the given render object.
  17955. *
  17956. * @param {RenderObject} renderObject - The render object.
  17957. */
  17958. updateForRender( renderObject ) {
  17959. this._updateBindings( this.getForRender( renderObject ) );
  17960. }
  17961. /**
  17962. * Updates the given array of bindings.
  17963. *
  17964. * @param {Array<BindGroup>} bindings - The bind groups.
  17965. */
  17966. _updateBindings( bindings ) {
  17967. for ( const bindGroup of bindings ) {
  17968. this._update( bindGroup, bindings );
  17969. }
  17970. }
  17971. /**
  17972. * Initializes the given bind group.
  17973. *
  17974. * @param {BindGroup} bindGroup - The bind group to initialize.
  17975. */
  17976. _init( bindGroup ) {
  17977. for ( const binding of bindGroup.bindings ) {
  17978. if ( binding.isSampledTexture ) {
  17979. this.textures.updateTexture( binding.texture );
  17980. } else if ( binding.isStorageBuffer ) {
  17981. const attribute = binding.attribute;
  17982. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  17983. this.attributes.update( attribute, attributeType );
  17984. }
  17985. }
  17986. }
  17987. /**
  17988. * Updates the given bind group.
  17989. *
  17990. * @param {BindGroup} bindGroup - The bind group to update.
  17991. * @param {Array<BindGroup>} bindings - The bind groups.
  17992. */
  17993. _update( bindGroup, bindings ) {
  17994. const { backend } = this;
  17995. let needsBindingsUpdate = false;
  17996. let cacheBindings = true;
  17997. let cacheIndex = 0;
  17998. let version = 0;
  17999. // iterate over all bindings and check if buffer updates or a new binding group is required
  18000. for ( const binding of bindGroup.bindings ) {
  18001. if ( binding.isNodeUniformsGroup ) {
  18002. const updated = this.nodes.updateGroup( binding );
  18003. // every uniforms group is a uniform buffer. So if no update is required,
  18004. // we move one with the next binding. Otherwise the next if block will update the group.
  18005. if ( updated === false ) continue;
  18006. }
  18007. if ( binding.isUniformBuffer ) {
  18008. const updated = binding.update();
  18009. if ( updated ) {
  18010. backend.updateBinding( binding );
  18011. }
  18012. } else if ( binding.isSampler ) {
  18013. binding.update();
  18014. } else if ( binding.isSampledTexture ) {
  18015. const texturesTextureData = this.textures.get( binding.texture );
  18016. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  18017. const updated = binding.update();
  18018. const texture = binding.texture;
  18019. if ( updated ) {
  18020. this.textures.updateTexture( texture );
  18021. }
  18022. const textureData = backend.get( texture );
  18023. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  18024. cacheBindings = false;
  18025. } else {
  18026. cacheIndex = cacheIndex * 10 + texture.id;
  18027. version += texture.version;
  18028. }
  18029. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  18030. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  18031. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  18032. this.textures.updateTexture( texture );
  18033. needsBindingsUpdate = true;
  18034. }
  18035. if ( texture.isStorageTexture === true ) {
  18036. const textureData = this.get( texture );
  18037. if ( binding.store === true ) {
  18038. textureData.needsMipmap = true;
  18039. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  18040. this.backend.generateMipmaps( texture );
  18041. textureData.needsMipmap = false;
  18042. }
  18043. }
  18044. }
  18045. }
  18046. if ( needsBindingsUpdate === true ) {
  18047. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  18048. }
  18049. }
  18050. }
  18051. /**
  18052. * Default sorting function for opaque render items.
  18053. *
  18054. * @private
  18055. * @function
  18056. * @param {Object} a - The first render item.
  18057. * @param {Object} b - The second render item.
  18058. * @return {Number} A numeric value which defines the sort order.
  18059. */
  18060. function painterSortStable( a, b ) {
  18061. if ( a.groupOrder !== b.groupOrder ) {
  18062. return a.groupOrder - b.groupOrder;
  18063. } else if ( a.renderOrder !== b.renderOrder ) {
  18064. return a.renderOrder - b.renderOrder;
  18065. } else if ( a.material.id !== b.material.id ) {
  18066. return a.material.id - b.material.id;
  18067. } else if ( a.z !== b.z ) {
  18068. return a.z - b.z;
  18069. } else {
  18070. return a.id - b.id;
  18071. }
  18072. }
  18073. /**
  18074. * Default sorting function for transparent render items.
  18075. *
  18076. * @private
  18077. * @function
  18078. * @param {Object} a - The first render item.
  18079. * @param {Object} b - The second render item.
  18080. * @return {Number} A numeric value which defines the sort order.
  18081. */
  18082. function reversePainterSortStable( a, b ) {
  18083. if ( a.groupOrder !== b.groupOrder ) {
  18084. return a.groupOrder - b.groupOrder;
  18085. } else if ( a.renderOrder !== b.renderOrder ) {
  18086. return a.renderOrder - b.renderOrder;
  18087. } else if ( a.z !== b.z ) {
  18088. return b.z - a.z;
  18089. } else {
  18090. return a.id - b.id;
  18091. }
  18092. }
  18093. /**
  18094. * Returns `true` if the given transparent material requires a double pass.
  18095. *
  18096. * @private
  18097. * @function
  18098. * @param {Material} material - The transparent material.
  18099. * @return {Boolean} Whether the given material requires a double pass or not.
  18100. */
  18101. function needsDoublePass( material ) {
  18102. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  18103. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  18104. }
  18105. /**
  18106. * When the renderer analyzes the scene at the beginning of a render call,
  18107. * it stores 3D object for further processing in render lists. Depending on the
  18108. * properties of a 3D objects (like their transformation or material state), the
  18109. * objects are maintained in ordered lists for the actual rendering.
  18110. *
  18111. * Render lists are unique per scene and camera combination.
  18112. *
  18113. * @private
  18114. * @augments Pipeline
  18115. */
  18116. class RenderList {
  18117. /**
  18118. * Constructs a render list.
  18119. *
  18120. * @param {Lighting} lighting - The lighting management component.
  18121. * @param {Scene} scene - The scene.
  18122. * @param {Camera} camera - The camera the scene is rendered with.
  18123. */
  18124. constructor( lighting, scene, camera ) {
  18125. /**
  18126. * 3D objects are transformed into render items and stored in this array.
  18127. *
  18128. * @type {Array<Object>}
  18129. */
  18130. this.renderItems = [];
  18131. /**
  18132. * The current render items index.
  18133. *
  18134. * @type {Number}
  18135. * @default 0
  18136. */
  18137. this.renderItemsIndex = 0;
  18138. /**
  18139. * A list with opaque render items.
  18140. *
  18141. * @type {Array<Object>}
  18142. */
  18143. this.opaque = [];
  18144. /**
  18145. * A list with transparent render items which require
  18146. * double pass rendering (e.g. transmissive objects).
  18147. *
  18148. * @type {Array<Object>}
  18149. */
  18150. this.transparentDoublePass = [];
  18151. /**
  18152. * A list with transparent render items.
  18153. *
  18154. * @type {Array<Object>}
  18155. */
  18156. this.transparent = [];
  18157. /**
  18158. * A list with transparent render bundle data.
  18159. *
  18160. * @type {Array<Object>}
  18161. */
  18162. this.bundles = [];
  18163. /**
  18164. * The render list's lights node. This node is later
  18165. * relevant for the actual analytical light nodes which
  18166. * compute the scene's lighting in the shader.
  18167. *
  18168. * @type {LightsNode}
  18169. */
  18170. this.lightsNode = lighting.getNode( scene, camera );
  18171. /**
  18172. * The scene's lights stored in an array. This array
  18173. * is used to setup the lights node.
  18174. *
  18175. * @type {Array<Light>}
  18176. */
  18177. this.lightsArray = [];
  18178. /**
  18179. * The scene.
  18180. *
  18181. * @type {Scene}
  18182. */
  18183. this.scene = scene;
  18184. /**
  18185. * The camera the scene is rendered with.
  18186. *
  18187. * @type {Camera}
  18188. */
  18189. this.camera = camera;
  18190. /**
  18191. * How many objects perform occlusion query tests.
  18192. *
  18193. * @type {Number}
  18194. * @default 0
  18195. */
  18196. this.occlusionQueryCount = 0;
  18197. }
  18198. /**
  18199. * This method is called right at the beginning of a render call
  18200. * before the scene is analyzed. It prepares the internal data
  18201. * structures for the upcoming render lists generation.
  18202. *
  18203. * @return {RenderList} A reference to this render list.
  18204. */
  18205. begin() {
  18206. this.renderItemsIndex = 0;
  18207. this.opaque.length = 0;
  18208. this.transparentDoublePass.length = 0;
  18209. this.transparent.length = 0;
  18210. this.bundles.length = 0;
  18211. this.lightsArray.length = 0;
  18212. this.occlusionQueryCount = 0;
  18213. return this;
  18214. }
  18215. /**
  18216. * Returns a render item for the giving render item state. The state is defined
  18217. * by a series of object-related parameters.
  18218. *
  18219. * The method avoids object creation by holding render items and reusing them in
  18220. * subsequent render calls (just with different property values).
  18221. *
  18222. * @param {Object3D} object - The 3D object.
  18223. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18224. * @param {Material} material - The 3D object's material.
  18225. * @param {Number} groupOrder - The current group order.
  18226. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18227. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18228. * @param {ClippingContext} clippingContext - The current clipping context.
  18229. * @return {Object} The render item.
  18230. */
  18231. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18232. let renderItem = this.renderItems[ this.renderItemsIndex ];
  18233. if ( renderItem === undefined ) {
  18234. renderItem = {
  18235. id: object.id,
  18236. object: object,
  18237. geometry: geometry,
  18238. material: material,
  18239. groupOrder: groupOrder,
  18240. renderOrder: object.renderOrder,
  18241. z: z,
  18242. group: group,
  18243. clippingContext: clippingContext
  18244. };
  18245. this.renderItems[ this.renderItemsIndex ] = renderItem;
  18246. } else {
  18247. renderItem.id = object.id;
  18248. renderItem.object = object;
  18249. renderItem.geometry = geometry;
  18250. renderItem.material = material;
  18251. renderItem.groupOrder = groupOrder;
  18252. renderItem.renderOrder = object.renderOrder;
  18253. renderItem.z = z;
  18254. renderItem.group = group;
  18255. renderItem.clippingContext = clippingContext;
  18256. }
  18257. this.renderItemsIndex ++;
  18258. return renderItem;
  18259. }
  18260. /**
  18261. * Pushes the given object as a render item to the internal render lists.
  18262. * The selected lists depend on the object properties.
  18263. *
  18264. * @param {Object3D} object - The 3D object.
  18265. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18266. * @param {Material} material - The 3D object's material.
  18267. * @param {Number} groupOrder - The current group order.
  18268. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18269. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18270. * @param {ClippingContext} clippingContext - The current clipping context.
  18271. */
  18272. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18273. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18274. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  18275. if ( material.transparent === true || material.transmission > 0 ) {
  18276. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  18277. this.transparent.push( renderItem );
  18278. } else {
  18279. this.opaque.push( renderItem );
  18280. }
  18281. }
  18282. /**
  18283. * Inserts the given object as a render item at the start of the internal render lists.
  18284. * The selected lists depend on the object properties.
  18285. *
  18286. * @param {Object3D} object - The 3D object.
  18287. * @param {BufferGeometry} geometry - The 3D object's geometry.
  18288. * @param {Material} material - The 3D object's material.
  18289. * @param {Number} groupOrder - The current group order.
  18290. * @param {Number} z - Th 3D object's depth value (z value in clip space).
  18291. * @param {Number?} group - {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  18292. * @param {ClippingContext} clippingContext - The current clipping context.
  18293. */
  18294. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  18295. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  18296. if ( material.transparent === true || material.transmission > 0 ) {
  18297. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  18298. this.transparent.unshift( renderItem );
  18299. } else {
  18300. this.opaque.unshift( renderItem );
  18301. }
  18302. }
  18303. /**
  18304. * Pushes render bundle group data into the render list.
  18305. *
  18306. * @param {Object} group - Bundle group data.
  18307. */
  18308. pushBundle( group ) {
  18309. this.bundles.push( group );
  18310. }
  18311. /**
  18312. * Pushes a light into the render list.
  18313. *
  18314. * @param {Light} light - The light.
  18315. */
  18316. pushLight( light ) {
  18317. this.lightsArray.push( light );
  18318. }
  18319. /**
  18320. * Sorts the internal render lists.
  18321. *
  18322. * @param {function(Any, Any): Number} customOpaqueSort - A custom sort function for opaque objects.
  18323. * @param {function(Any, Any): Number} customTransparentSort - A custom sort function for transparent objects.
  18324. */
  18325. sort( customOpaqueSort, customTransparentSort ) {
  18326. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  18327. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  18328. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  18329. }
  18330. /**
  18331. * This method performs finalizing tasks right after the render lists
  18332. * have been generated.
  18333. */
  18334. finish() {
  18335. // update lights
  18336. this.lightsNode.setLights( this.lightsArray );
  18337. // Clear references from inactive renderItems in the list
  18338. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  18339. const renderItem = this.renderItems[ i ];
  18340. if ( renderItem.id === null ) break;
  18341. renderItem.id = null;
  18342. renderItem.object = null;
  18343. renderItem.geometry = null;
  18344. renderItem.material = null;
  18345. renderItem.groupOrder = null;
  18346. renderItem.renderOrder = null;
  18347. renderItem.z = null;
  18348. renderItem.group = null;
  18349. renderItem.clippingContext = null;
  18350. }
  18351. }
  18352. }
  18353. const _chainKeys$4 = [];
  18354. /**
  18355. * This renderer module manages the render lists which are unique
  18356. * per scene and camera combination.
  18357. *
  18358. * @private
  18359. */
  18360. class RenderLists {
  18361. /**
  18362. * Constructs a render lists management component.
  18363. *
  18364. * @param {Lighting} lighting - The lighting management component.
  18365. */
  18366. constructor( lighting ) {
  18367. /**
  18368. * The lighting management component.
  18369. *
  18370. * @type {Lighting}
  18371. */
  18372. this.lighting = lighting;
  18373. /**
  18374. * The internal chain map which holds the render lists.
  18375. *
  18376. * @type {ChainMap}
  18377. */
  18378. this.lists = new ChainMap();
  18379. }
  18380. /**
  18381. * Returns a render list for the given scene and camera.
  18382. *
  18383. * @param {Scene} scene - The scene.
  18384. * @param {Camera} camera - The camera.
  18385. * @return {RenderList} The render list.
  18386. */
  18387. get( scene, camera ) {
  18388. const lists = this.lists;
  18389. _chainKeys$4[ 0 ] = scene;
  18390. _chainKeys$4[ 1 ] = camera;
  18391. let list = lists.get( _chainKeys$4 );
  18392. if ( list === undefined ) {
  18393. list = new RenderList( this.lighting, scene, camera );
  18394. lists.set( _chainKeys$4, list );
  18395. }
  18396. _chainKeys$4.length = 0;
  18397. return list;
  18398. }
  18399. /**
  18400. * Frees all internal resources.
  18401. */
  18402. dispose() {
  18403. this.lists = new ChainMap();
  18404. }
  18405. }
  18406. let _id$7 = 0;
  18407. /**
  18408. * Any render or compute command is executed in a specific context that defines
  18409. * the state of the renderer and its backend. Typical examples for such context
  18410. * data are the current clear values or data from the active framebuffer. This
  18411. * module is used to represent these contexts as objects.
  18412. *
  18413. * @private
  18414. */
  18415. class RenderContext {
  18416. /**
  18417. * Constructs a new render context.
  18418. */
  18419. constructor() {
  18420. /**
  18421. * The context's ID.
  18422. *
  18423. * @type {Number}
  18424. */
  18425. this.id = _id$7 ++;
  18426. /**
  18427. * Whether the current active framebuffer has a color attachment.
  18428. *
  18429. * @type {Boolean}
  18430. * @default true
  18431. */
  18432. this.color = true;
  18433. /**
  18434. * Whether the color attachment should be cleared or not.
  18435. *
  18436. * @type {Boolean}
  18437. * @default true
  18438. */
  18439. this.clearColor = true;
  18440. /**
  18441. * The clear color value.
  18442. *
  18443. * @type {Object}
  18444. * @default true
  18445. */
  18446. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  18447. /**
  18448. * Whether the current active framebuffer has a depth attachment.
  18449. *
  18450. * @type {Boolean}
  18451. * @default true
  18452. */
  18453. this.depth = true;
  18454. /**
  18455. * Whether the depth attachment should be cleared or not.
  18456. *
  18457. * @type {Boolean}
  18458. * @default true
  18459. */
  18460. this.clearDepth = true;
  18461. /**
  18462. * The clear depth value.
  18463. *
  18464. * @type {Number}
  18465. * @default 1
  18466. */
  18467. this.clearDepthValue = 1;
  18468. /**
  18469. * Whether the current active framebuffer has a stencil attachment.
  18470. *
  18471. * @type {Boolean}
  18472. * @default false
  18473. */
  18474. this.stencil = false;
  18475. /**
  18476. * Whether the stencil attachment should be cleared or not.
  18477. *
  18478. * @type {Boolean}
  18479. * @default true
  18480. */
  18481. this.clearStencil = true;
  18482. /**
  18483. * The clear stencil value.
  18484. *
  18485. * @type {Number}
  18486. * @default 1
  18487. */
  18488. this.clearStencilValue = 1;
  18489. /**
  18490. * By default the viewport encloses the entire framebuffer If a smaller
  18491. * viewport is manually defined, this property is to `true` by the renderer.
  18492. *
  18493. * @type {Boolean}
  18494. * @default false
  18495. */
  18496. this.viewport = false;
  18497. /**
  18498. * The viewport value. This value is in physical pixels meaning it incorporates
  18499. * the renderer's pixel ratio. The viewport property of render targets or
  18500. * the renderer is in logical pixels.
  18501. *
  18502. * @type {Vector4}
  18503. */
  18504. this.viewportValue = new Vector4();
  18505. /**
  18506. * When the scissor test is active and scissor rectangle smaller than the
  18507. * framebuffers dimensions, this property is to `true` by the renderer.
  18508. *
  18509. * @type {Boolean}
  18510. * @default false
  18511. */
  18512. this.scissor = false;
  18513. /**
  18514. * The scissor rectangle.
  18515. *
  18516. * @type {Vector4}
  18517. */
  18518. this.scissorValue = new Vector4();
  18519. /**
  18520. * The active render target.
  18521. *
  18522. * @type {RenderTarget?}
  18523. * @default null
  18524. */
  18525. this.renderTarget = null;
  18526. /**
  18527. * The textures of the active render target.
  18528. * `null` when no render target is set.
  18529. *
  18530. * @type {Array<Texture>?}
  18531. * @default null
  18532. */
  18533. this.textures = null;
  18534. /**
  18535. * The depth texture of the active render target.
  18536. * `null` when no render target is set.
  18537. *
  18538. * @type {DepthTexture?}
  18539. * @default null
  18540. */
  18541. this.depthTexture = null;
  18542. /**
  18543. * The active cube face.
  18544. *
  18545. * @type {Number}
  18546. * @default 0
  18547. */
  18548. this.activeCubeFace = 0;
  18549. /**
  18550. * The active mipmap level.
  18551. *
  18552. * @type {Number}
  18553. * @default 0
  18554. */
  18555. this.activeMipmapLevel = 0;
  18556. /**
  18557. * The number of MSAA samples. This value is always `1` when
  18558. * MSAA isn't used.
  18559. *
  18560. * @type {Number}
  18561. * @default 1
  18562. */
  18563. this.sampleCount = 1;
  18564. /**
  18565. * The active render target's width in physical pixels.
  18566. *
  18567. * @type {Number}
  18568. * @default 0
  18569. */
  18570. this.width = 0;
  18571. /**
  18572. * The active render target's height in physical pixels.
  18573. *
  18574. * @type {Number}
  18575. * @default 0
  18576. */
  18577. this.height = 0;
  18578. /**
  18579. * The occlusion query count.
  18580. *
  18581. * @type {Number}
  18582. * @default 0
  18583. */
  18584. this.occlusionQueryCount = 0;
  18585. /**
  18586. * The current clipping context.
  18587. *
  18588. * @type {ClippingContext?}
  18589. * @default null
  18590. */
  18591. this.clippingContext = null;
  18592. /**
  18593. * This flag can be used for type testing.
  18594. *
  18595. * @type {Boolean}
  18596. * @readonly
  18597. * @default true
  18598. */
  18599. this.isRenderContext = true;
  18600. }
  18601. /**
  18602. * Returns the cache key of this render context.
  18603. *
  18604. * @return {Number} The cache key.
  18605. */
  18606. getCacheKey() {
  18607. return getCacheKey( this );
  18608. }
  18609. }
  18610. /**
  18611. * Computes a cache key for the given render context. This key
  18612. * should identify the render target state so it is possible to
  18613. * configure the correct attachments in the respective backend.
  18614. *
  18615. * @param {RenderContext} renderContext - The render context.
  18616. * @return {Number} The cache key.
  18617. */
  18618. function getCacheKey( renderContext ) {
  18619. const { textures, activeCubeFace } = renderContext;
  18620. const values = [ activeCubeFace ];
  18621. for ( const texture of textures ) {
  18622. values.push( texture.id );
  18623. }
  18624. return hashArray( values );
  18625. }
  18626. const _chainKeys$3 = [];
  18627. const _defaultScene = /*@__PURE__*/ new Scene();
  18628. const _defaultCamera = /*@__PURE__*/ new Camera();
  18629. /**
  18630. * This module manages the render contexts of the renderer.
  18631. *
  18632. * @private
  18633. */
  18634. class RenderContexts {
  18635. /**
  18636. * Constructs a new render context management component.
  18637. */
  18638. constructor() {
  18639. /**
  18640. * A dictionary that manages render contexts in chain maps
  18641. * for each attachment state.
  18642. *
  18643. * @type {Object<String,ChainMap>}
  18644. */
  18645. this.chainMaps = {};
  18646. }
  18647. /**
  18648. * Returns a render context for the given scene, camera and render target.
  18649. *
  18650. * @param {Scene} scene - The scene.
  18651. * @param {Camera} camera - The camera that is used to render the scene.
  18652. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18653. * @return {RenderContext} The render context.
  18654. */
  18655. get( scene, camera, renderTarget = null ) {
  18656. _chainKeys$3[ 0 ] = scene;
  18657. _chainKeys$3[ 1 ] = camera;
  18658. let attachmentState;
  18659. if ( renderTarget === null ) {
  18660. attachmentState = 'default';
  18661. } else {
  18662. const format = renderTarget.texture.format;
  18663. const count = renderTarget.textures.length;
  18664. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  18665. }
  18666. const chainMap = this._getChainMap( attachmentState );
  18667. let renderState = chainMap.get( _chainKeys$3 );
  18668. if ( renderState === undefined ) {
  18669. renderState = new RenderContext();
  18670. chainMap.set( _chainKeys$3, renderState );
  18671. }
  18672. _chainKeys$3.length = 0;
  18673. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18674. return renderState;
  18675. }
  18676. /**
  18677. * Returns a render context intended for clear operations.
  18678. *
  18679. * @param {RenderTarget?} [renderTarget=null] - The active render target.
  18680. * @return {RenderContext} The render context.
  18681. */
  18682. getForClear( renderTarget = null ) {
  18683. return this.get( _defaultScene, _defaultCamera, renderTarget );
  18684. }
  18685. /**
  18686. * Returns a chain map for the given attachment state.
  18687. *
  18688. * @private
  18689. * @param {String} attachmentState - The attachment state.
  18690. * @return {ChainMap} The chain map.
  18691. */
  18692. _getChainMap( attachmentState ) {
  18693. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  18694. }
  18695. /**
  18696. * Frees internal resources.
  18697. */
  18698. dispose() {
  18699. this.chainMaps = {};
  18700. }
  18701. }
  18702. const _size$3 = /*@__PURE__*/ new Vector3();
  18703. /**
  18704. * This module manages the textures of the renderer.
  18705. *
  18706. * @private
  18707. * @augments DataMap
  18708. */
  18709. class Textures extends DataMap {
  18710. /**
  18711. * Constructs a new texture management component.
  18712. *
  18713. * @param {Renderer} renderer - The renderer.
  18714. * @param {Backend} backend - The renderer's backend.
  18715. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18716. */
  18717. constructor( renderer, backend, info ) {
  18718. super();
  18719. /**
  18720. * The renderer.
  18721. *
  18722. * @type {Renderer}
  18723. */
  18724. this.renderer = renderer;
  18725. /**
  18726. * The backend.
  18727. *
  18728. * @type {Backend}
  18729. */
  18730. this.backend = backend;
  18731. /**
  18732. * Renderer component for managing metrics and monitoring data.
  18733. *
  18734. * @type {Info}
  18735. */
  18736. this.info = info;
  18737. }
  18738. /**
  18739. * Updates the given render target. Based on the given render target configuration,
  18740. * it updates the texture states representing the attachments of the framebuffer.
  18741. *
  18742. * @param {RenderTarget} renderTarget - The render target to update.
  18743. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  18744. */
  18745. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  18746. const renderTargetData = this.get( renderTarget );
  18747. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  18748. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  18749. const textures = renderTarget.textures;
  18750. const size = this.getSize( textures[ 0 ] );
  18751. const mipWidth = size.width >> activeMipmapLevel;
  18752. const mipHeight = size.height >> activeMipmapLevel;
  18753. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  18754. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  18755. let textureNeedsUpdate = false;
  18756. if ( depthTexture === undefined && useDepthTexture ) {
  18757. depthTexture = new DepthTexture();
  18758. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  18759. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  18760. depthTexture.image.width = mipWidth;
  18761. depthTexture.image.height = mipHeight;
  18762. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  18763. }
  18764. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  18765. textureNeedsUpdate = true;
  18766. if ( depthTexture ) {
  18767. depthTexture.needsUpdate = true;
  18768. depthTexture.image.width = mipWidth;
  18769. depthTexture.image.height = mipHeight;
  18770. }
  18771. }
  18772. renderTargetData.width = size.width;
  18773. renderTargetData.height = size.height;
  18774. renderTargetData.textures = textures;
  18775. renderTargetData.depthTexture = depthTexture || null;
  18776. renderTargetData.depth = renderTarget.depthBuffer;
  18777. renderTargetData.stencil = renderTarget.stencilBuffer;
  18778. renderTargetData.renderTarget = renderTarget;
  18779. if ( renderTargetData.sampleCount !== sampleCount ) {
  18780. textureNeedsUpdate = true;
  18781. if ( depthTexture ) {
  18782. depthTexture.needsUpdate = true;
  18783. }
  18784. renderTargetData.sampleCount = sampleCount;
  18785. }
  18786. //
  18787. const options = { sampleCount };
  18788. for ( let i = 0; i < textures.length; i ++ ) {
  18789. const texture = textures[ i ];
  18790. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  18791. this.updateTexture( texture, options );
  18792. }
  18793. if ( depthTexture ) {
  18794. this.updateTexture( depthTexture, options );
  18795. }
  18796. // dispose handler
  18797. if ( renderTargetData.initialized !== true ) {
  18798. renderTargetData.initialized = true;
  18799. // dispose
  18800. const onDispose = () => {
  18801. renderTarget.removeEventListener( 'dispose', onDispose );
  18802. for ( let i = 0; i < textures.length; i ++ ) {
  18803. this._destroyTexture( textures[ i ] );
  18804. }
  18805. if ( depthTexture ) {
  18806. this._destroyTexture( depthTexture );
  18807. }
  18808. this.delete( renderTarget );
  18809. };
  18810. renderTarget.addEventListener( 'dispose', onDispose );
  18811. }
  18812. }
  18813. /**
  18814. * Updates the given texture. Depending on the texture state, this method
  18815. * triggers the upload of texture data to the GPU memory. If the texture data are
  18816. * not yet ready for the upload, it uses default texture data for as a placeholder.
  18817. *
  18818. * @param {Texture} texture - The texture to update.
  18819. * @param {Object} [options={}] - The options.
  18820. */
  18821. updateTexture( texture, options = {} ) {
  18822. const textureData = this.get( texture );
  18823. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  18824. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  18825. const backend = this.backend;
  18826. if ( isRenderTarget && textureData.initialized === true ) {
  18827. // it's an update
  18828. backend.destroySampler( texture );
  18829. backend.destroyTexture( texture );
  18830. }
  18831. //
  18832. if ( texture.isFramebufferTexture ) {
  18833. const renderTarget = this.renderer.getRenderTarget();
  18834. if ( renderTarget ) {
  18835. texture.type = renderTarget.texture.type;
  18836. } else {
  18837. texture.type = UnsignedByteType;
  18838. }
  18839. }
  18840. //
  18841. const { width, height, depth } = this.getSize( texture );
  18842. options.width = width;
  18843. options.height = height;
  18844. options.depth = depth;
  18845. options.needsMipmaps = this.needsMipmaps( texture );
  18846. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  18847. //
  18848. if ( isRenderTarget || texture.isStorageTexture === true ) {
  18849. backend.createSampler( texture );
  18850. backend.createTexture( texture, options );
  18851. textureData.generation = texture.version;
  18852. } else {
  18853. const needsCreate = textureData.initialized !== true;
  18854. if ( needsCreate ) backend.createSampler( texture );
  18855. if ( texture.version > 0 ) {
  18856. const image = texture.image;
  18857. if ( image === undefined ) {
  18858. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  18859. } else if ( image.complete === false ) {
  18860. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  18861. } else {
  18862. if ( texture.images ) {
  18863. const images = [];
  18864. for ( const image of texture.images ) {
  18865. images.push( image );
  18866. }
  18867. options.images = images;
  18868. } else {
  18869. options.image = image;
  18870. }
  18871. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  18872. backend.createTexture( texture, options );
  18873. textureData.isDefaultTexture = false;
  18874. textureData.generation = texture.version;
  18875. }
  18876. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  18877. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  18878. }
  18879. } else {
  18880. // async update
  18881. backend.createDefaultTexture( texture );
  18882. textureData.isDefaultTexture = true;
  18883. textureData.generation = texture.version;
  18884. }
  18885. }
  18886. // dispose handler
  18887. if ( textureData.initialized !== true ) {
  18888. textureData.initialized = true;
  18889. textureData.generation = texture.version;
  18890. //
  18891. this.info.memory.textures ++;
  18892. // dispose
  18893. const onDispose = () => {
  18894. texture.removeEventListener( 'dispose', onDispose );
  18895. this._destroyTexture( texture );
  18896. this.info.memory.textures --;
  18897. };
  18898. texture.addEventListener( 'dispose', onDispose );
  18899. }
  18900. //
  18901. textureData.version = texture.version;
  18902. }
  18903. /**
  18904. * Computes the size of the given texture and writes the result
  18905. * into the target vector. This vector is also returned by the
  18906. * method.
  18907. *
  18908. * If no texture data are available for the compute yet, the method
  18909. * returns default size values.
  18910. *
  18911. * @param {Texture} texture - The texture to compute the size for.
  18912. * @param {Vector3} target - The target vector.
  18913. * @return {Vector3} The target vector.
  18914. */
  18915. getSize( texture, target = _size$3 ) {
  18916. let image = texture.images ? texture.images[ 0 ] : texture.image;
  18917. if ( image ) {
  18918. if ( image.image !== undefined ) image = image.image;
  18919. target.width = image.width || 1;
  18920. target.height = image.height || 1;
  18921. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  18922. } else {
  18923. target.width = target.height = target.depth = 1;
  18924. }
  18925. return target;
  18926. }
  18927. /**
  18928. * Computes the number of mipmap levels for the given texture.
  18929. *
  18930. * @param {Texture} texture - The texture.
  18931. * @param {Number} width - The texture's width.
  18932. * @param {Number} height - The texture's height.
  18933. * @return {Number} The number of mipmap levels.
  18934. */
  18935. getMipLevels( texture, width, height ) {
  18936. let mipLevelCount;
  18937. if ( texture.isCompressedTexture ) {
  18938. if ( texture.mipmaps ) {
  18939. mipLevelCount = texture.mipmaps.length;
  18940. } else {
  18941. mipLevelCount = 1;
  18942. }
  18943. } else {
  18944. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  18945. }
  18946. return mipLevelCount;
  18947. }
  18948. /**
  18949. * Returns `true` if the given texture requires mipmaps.
  18950. *
  18951. * @param {Texture} texture - The texture.
  18952. * @return {Boolean} Whether mipmaps are required or not.
  18953. */
  18954. needsMipmaps( texture ) {
  18955. return this.isEnvironmentTexture( texture ) || texture.isCompressedTexture === true || texture.generateMipmaps;
  18956. }
  18957. /**
  18958. * Returns `true` if the given texture is an environment map.
  18959. *
  18960. * @param {Texture} texture - The texture.
  18961. * @return {Boolean} Whether the given texture is an environment map or not.
  18962. */
  18963. isEnvironmentTexture( texture ) {
  18964. const mapping = texture.mapping;
  18965. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  18966. }
  18967. /**
  18968. * Frees internal resource when the given texture isn't
  18969. * required anymore.
  18970. *
  18971. * @param {Texture} texture - The texture to destroy.
  18972. */
  18973. _destroyTexture( texture ) {
  18974. this.backend.destroySampler( texture );
  18975. this.backend.destroyTexture( texture );
  18976. this.delete( texture );
  18977. }
  18978. }
  18979. /**
  18980. * A four-component version of {@link Color} which is internally
  18981. * used by the renderer to represents clear color with alpha as
  18982. * one object.
  18983. *
  18984. * @private
  18985. * @augments Color
  18986. */
  18987. class Color4 extends Color {
  18988. /**
  18989. * Constructs a new four-component color.
  18990. * You can also pass a single THREE.Color, hex or
  18991. * string argument to this constructor.
  18992. *
  18993. * @param {Number|String} [r=1] - The red value.
  18994. * @param {Number} [g=1] - The green value.
  18995. * @param {Number} [b=1] - The blue value.
  18996. * @param {Number} [a=1] - The alpha value.
  18997. */
  18998. constructor( r, g, b, a = 1 ) {
  18999. super( r, g, b );
  19000. this.a = a;
  19001. }
  19002. /**
  19003. * Overwrites the default to honor alpha.
  19004. * You can also pass a single THREE.Color, hex or
  19005. * string argument to this method.
  19006. *
  19007. * @param {Number|String} r - The red value.
  19008. * @param {Number} g - The green value.
  19009. * @param {Number} b - The blue value.
  19010. * @param {Number} [a=1] - The alpha value.
  19011. * @return {Color4} A reference to this object.
  19012. */
  19013. set( r, g, b, a = 1 ) {
  19014. this.a = a;
  19015. return super.set( r, g, b );
  19016. }
  19017. /**
  19018. * Overwrites the default to honor alpha.
  19019. *
  19020. * @param {Color4} color - The color to copy.
  19021. * @return {Color4} A reference to this object.
  19022. */
  19023. copy( color ) {
  19024. if ( color.a !== undefined ) this.a = color.a;
  19025. return super.copy( color );
  19026. }
  19027. /**
  19028. * Overwrites the default to honor alpha.
  19029. *
  19030. * @return {Color4} The cloned color.
  19031. */
  19032. clone() {
  19033. return new this.constructor( this.r, this.g, this.b, this.a );
  19034. }
  19035. }
  19036. /** @module ParameterNode **/
  19037. /**
  19038. * Special version of {@link PropertyNode} which is used for parameters.
  19039. *
  19040. * @augments PropertyNode
  19041. */
  19042. class ParameterNode extends PropertyNode {
  19043. static get type() {
  19044. return 'ParameterNode';
  19045. }
  19046. /**
  19047. * Constructs a new parameter node.
  19048. *
  19049. * @param {String} nodeType - The type of the node.
  19050. * @param {String?} [name=null] - The name of the parameter in the shader.
  19051. */
  19052. constructor( nodeType, name = null ) {
  19053. super( nodeType, name );
  19054. /**
  19055. * This flag can be used for type testing.
  19056. *
  19057. * @type {Boolean}
  19058. * @readonly
  19059. * @default true
  19060. */
  19061. this.isParameterNode = true;
  19062. }
  19063. getHash() {
  19064. return this.uuid;
  19065. }
  19066. generate() {
  19067. return this.name;
  19068. }
  19069. }
  19070. /**
  19071. * TSL function for creating a parameter node.
  19072. *
  19073. * @function
  19074. * @param {String} type - The type of the node.
  19075. * @param {String?} name - The name of the parameter in the shader.
  19076. * @returns {ParameterNode}
  19077. */
  19078. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  19079. /** @module StackNode **/
  19080. /**
  19081. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  19082. * They are usually needed in cases like `If`, `Else`.
  19083. *
  19084. * @augments Node
  19085. */
  19086. class StackNode extends Node {
  19087. static get type() {
  19088. return 'StackNode';
  19089. }
  19090. /**
  19091. * Constructs a new stack node.
  19092. *
  19093. * @param {StackNode?} [parent=null] - The parent stack node.
  19094. */
  19095. constructor( parent = null ) {
  19096. super();
  19097. /**
  19098. * List of nodes.
  19099. *
  19100. * @type {Array<Node>}
  19101. */
  19102. this.nodes = [];
  19103. /**
  19104. * The output node.
  19105. *
  19106. * @type {Node?}
  19107. * @default null
  19108. */
  19109. this.outputNode = null;
  19110. /**
  19111. * The parent stack node.
  19112. *
  19113. * @type {StackNode}
  19114. * @default null
  19115. */
  19116. this.parent = parent;
  19117. /**
  19118. * The current conditional node.
  19119. *
  19120. * @private
  19121. * @type {ConditionalNode}
  19122. * @default null
  19123. */
  19124. this._currentCond = null;
  19125. /**
  19126. * This flag can be used for type testing.
  19127. *
  19128. * @type {Boolean}
  19129. * @readonly
  19130. * @default true
  19131. */
  19132. this.isStackNode = true;
  19133. }
  19134. getNodeType( builder ) {
  19135. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  19136. }
  19137. /**
  19138. * Adds a node to this stack.
  19139. *
  19140. * @param {Node} node - The node to add.
  19141. * @return {StackNode} A reference to this stack node.
  19142. */
  19143. add( node ) {
  19144. this.nodes.push( node );
  19145. return this;
  19146. }
  19147. /**
  19148. * Represent an `if` statement in TSL.
  19149. *
  19150. * @param {Node} boolNode - Represents the condition.
  19151. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19152. * @return {StackNode} A reference to this stack node.
  19153. */
  19154. If( boolNode, method ) {
  19155. const methodNode = new ShaderNode( method );
  19156. this._currentCond = select( boolNode, methodNode );
  19157. return this.add( this._currentCond );
  19158. }
  19159. /**
  19160. * Represent an `elseif` statement in TSL.
  19161. *
  19162. * @param {Node} boolNode - Represents the condition.
  19163. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  19164. * @return {StackNode} A reference to this stack node.
  19165. */
  19166. ElseIf( boolNode, method ) {
  19167. const methodNode = new ShaderNode( method );
  19168. const ifNode = select( boolNode, methodNode );
  19169. this._currentCond.elseNode = ifNode;
  19170. this._currentCond = ifNode;
  19171. return this;
  19172. }
  19173. /**
  19174. * Represent an `else` statement in TSL.
  19175. *
  19176. * @param {Function} method - TSL code which is executed in the `else` case.
  19177. * @return {StackNode} A reference to this stack node.
  19178. */
  19179. Else( method ) {
  19180. this._currentCond.elseNode = new ShaderNode( method );
  19181. return this;
  19182. }
  19183. build( builder, ...params ) {
  19184. const previousStack = getCurrentStack();
  19185. setCurrentStack( this );
  19186. for ( const node of this.nodes ) {
  19187. node.build( builder, 'void' );
  19188. }
  19189. setCurrentStack( previousStack );
  19190. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  19191. }
  19192. // deprecated
  19193. /**
  19194. * @function
  19195. * @deprecated since r168. Use {@link StackNode#Else} instead.
  19196. *
  19197. * @param {...any} params
  19198. * @returns {StackNode}
  19199. */
  19200. else( ...params ) { // @deprecated, r168
  19201. console.warn( 'TSL.StackNode: .else() has been renamed to .Else().' );
  19202. return this.Else( ...params );
  19203. }
  19204. /**
  19205. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  19206. *
  19207. * @param {...any} params
  19208. * @returns {StackNode}
  19209. */
  19210. elseif( ...params ) { // @deprecated, r168
  19211. console.warn( 'TSL.StackNode: .elseif() has been renamed to .ElseIf().' );
  19212. return this.ElseIf( ...params );
  19213. }
  19214. }
  19215. /**
  19216. * TSL function for creating a stack node.
  19217. *
  19218. * @function
  19219. * @param {StackNode?} [parent=null] - The parent stack node.
  19220. * @returns {StackNode}
  19221. */
  19222. const stack = /*@__PURE__*/ nodeProxy( StackNode );
  19223. /** @module OutputStructNode **/
  19224. /**
  19225. * This node can be used to define multiple outputs in a shader programs.
  19226. *
  19227. * @augments Node
  19228. */
  19229. class OutputStructNode extends Node {
  19230. static get type() {
  19231. return 'OutputStructNode';
  19232. }
  19233. /**
  19234. * Constructs a new output struct node. The constructor can be invoked with an
  19235. * arbitrary number of nodes representing the members.
  19236. *
  19237. * @param {...Node} members - A parameter list of nodes.
  19238. */
  19239. constructor( ...members ) {
  19240. super();
  19241. /**
  19242. * An array of nodes which defines the output.
  19243. *
  19244. * @type {Array<Node>}
  19245. */
  19246. this.members = members;
  19247. /**
  19248. * This flag can be used for type testing.
  19249. *
  19250. * @type {Boolean}
  19251. * @readonly
  19252. * @default true
  19253. */
  19254. this.isOutputStructNode = true;
  19255. }
  19256. setup( builder ) {
  19257. super.setup( builder );
  19258. const members = this.members;
  19259. const types = [];
  19260. for ( let i = 0; i < members.length; i ++ ) {
  19261. types.push( members[ i ].getNodeType( builder ) );
  19262. }
  19263. this.nodeType = builder.getStructTypeFromNode( this, types ).name;
  19264. }
  19265. generate( builder, output ) {
  19266. const propertyName = builder.getOutputStructName();
  19267. const members = this.members;
  19268. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  19269. for ( let i = 0; i < members.length; i ++ ) {
  19270. const snippet = members[ i ].build( builder, output );
  19271. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  19272. }
  19273. return propertyName;
  19274. }
  19275. }
  19276. /**
  19277. * TSL function for creating an output struct node.
  19278. *
  19279. * @function
  19280. * @param {...Node} members - A parameter list of nodes.
  19281. * @returns {OutputStructNode}
  19282. */
  19283. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  19284. /** @module MRTNode **/
  19285. /**
  19286. * Returns the MRT texture index for the given name.
  19287. *
  19288. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  19289. * @param {String} name - The name of the MRT texture which index is requested.
  19290. * @return {Number} The texture index.
  19291. */
  19292. function getTextureIndex( textures, name ) {
  19293. for ( let i = 0; i < textures.length; i ++ ) {
  19294. if ( textures[ i ].name === name ) {
  19295. return i;
  19296. }
  19297. }
  19298. return - 1;
  19299. }
  19300. /**
  19301. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  19302. * post-processing is shown below:
  19303. * ```js
  19304. * const mrtNode = mrt( {
  19305. * output: output,
  19306. * normal: normalView
  19307. * } ) );
  19308. * ```
  19309. * The MRT output is defined as a dictionary.
  19310. *
  19311. * @augments OutputStructNode
  19312. */
  19313. class MRTNode extends OutputStructNode {
  19314. static get type() {
  19315. return 'MRTNode';
  19316. }
  19317. /**
  19318. * Constructs a new output struct node.
  19319. *
  19320. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19321. */
  19322. constructor( outputNodes ) {
  19323. super();
  19324. /**
  19325. * A dictionary representing the MRT outputs. The key
  19326. * is the name of the output, the value the node which produces
  19327. * the output result.
  19328. *
  19329. * @type {Object<String, Node>}
  19330. */
  19331. this.outputNodes = outputNodes;
  19332. /**
  19333. * This flag can be used for type testing.
  19334. *
  19335. * @type {Boolean}
  19336. * @readonly
  19337. * @default true
  19338. */
  19339. this.isMRTNode = true;
  19340. }
  19341. /**
  19342. * Returns `true` if the MRT node has an output with the given name.
  19343. *
  19344. * @param {String} name - The name of the output.
  19345. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  19346. */
  19347. has( name ) {
  19348. return this.outputNodes[ name ] !== undefined;
  19349. }
  19350. /**
  19351. * Returns the output node for the given name.
  19352. *
  19353. * @param {String} name - The name of the output.
  19354. * @return {Node} The output node.
  19355. */
  19356. get( name ) {
  19357. return this.outputNodes[ name ];
  19358. }
  19359. /**
  19360. * Merges the outputs of the given MRT node with the outputs of this node.
  19361. *
  19362. * @param {MRTNode} mrtNode - The MRT to merge.
  19363. * @return {MRTNode} A new MRT node with merged outputs..
  19364. */
  19365. merge( mrtNode ) {
  19366. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  19367. return mrt( outputs );
  19368. }
  19369. setup( builder ) {
  19370. const outputNodes = this.outputNodes;
  19371. const mrt = builder.renderer.getRenderTarget();
  19372. const members = [];
  19373. const textures = mrt.textures;
  19374. for ( const name in outputNodes ) {
  19375. const index = getTextureIndex( textures, name );
  19376. members[ index ] = vec4( outputNodes[ name ] );
  19377. }
  19378. this.members = members;
  19379. return super.setup( builder );
  19380. }
  19381. }
  19382. /**
  19383. * TSL function for creating a MRT node.
  19384. *
  19385. * @function
  19386. * @param {Object<String, Node>} outputNodes - The MRT outputs.
  19387. * @returns {MRTNode}
  19388. */
  19389. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  19390. /** @module Hash **/
  19391. /**
  19392. * Generates a hash value in the range `[0, 1]` from the given seed.
  19393. *
  19394. * @method
  19395. * @param {Node<float>} seed - The seed.
  19396. * @return {Node<float>} The hash value.
  19397. */
  19398. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  19399. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  19400. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  19401. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  19402. const result = word.shiftRight( 22 ).bitXor( word );
  19403. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  19404. } );
  19405. /** @module MathUtils **/
  19406. /**
  19407. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19408. * The corners are mapped to `0` and the center to `1`.
  19409. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19410. *
  19411. * @method
  19412. * @param {Node<float>} x - The value to remap.
  19413. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  19414. * @return {Node<float>} The remapped value.
  19415. */
  19416. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  19417. /**
  19418. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19419. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  19420. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19421. *
  19422. * @method
  19423. * @param {Node<float>} x - The value to remap.
  19424. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  19425. * @return {Node<float>} The remapped value.
  19426. */
  19427. 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 ) );
  19428. /**
  19429. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  19430. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  19431. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19432. *
  19433. * @method
  19434. * @param {Node<float>} x - The value to remap.
  19435. * @param {Node<float>} a - First control parameter.
  19436. * @param {Node<float>} b - Second control parameter.
  19437. * @return {Node<float>} The remapped value.
  19438. */
  19439. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  19440. /**
  19441. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  19442. * Reference: {@link https://iquilezles.org/articles/functions/}.
  19443. *
  19444. * @method
  19445. * @param {Node<float>} x - The value to compute the sin for.
  19446. * @param {Node<float>} k - Controls the amount of bounces.
  19447. * @return {Node<float>} The result value.
  19448. */
  19449. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  19450. // https://github.com/cabbibo/glsl-tri-noise-3d
  19451. /** @module TriNoise3D **/
  19452. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  19453. return x.fract().sub( .5 ).abs();
  19454. } ).setLayout( {
  19455. name: 'tri',
  19456. type: 'float',
  19457. inputs: [
  19458. { name: 'x', type: 'float' }
  19459. ]
  19460. } );
  19461. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  19462. 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. ) ) ) ) );
  19463. } ).setLayout( {
  19464. name: 'tri3',
  19465. type: 'vec3',
  19466. inputs: [
  19467. { name: 'p', type: 'vec3' }
  19468. ]
  19469. } );
  19470. /**
  19471. * Generates a noise value from the given position, speed and time parameters.
  19472. *
  19473. * @method
  19474. * @param {Node<vec3>} position - The position.
  19475. * @param {Node<float>} speed - The speed.
  19476. * @param {Node<float>} time - The time.
  19477. * @return {Node<float>} The generated noise.
  19478. */
  19479. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  19480. const p = vec3( position ).toVar();
  19481. const z = float( 1.4 ).toVar();
  19482. const rz = float( 0.0 ).toVar();
  19483. const bp = vec3( p ).toVar();
  19484. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  19485. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  19486. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  19487. bp.mulAssign( 1.8 );
  19488. z.mulAssign( 1.5 );
  19489. p.mulAssign( 1.2 );
  19490. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  19491. rz.addAssign( t.div( z ) );
  19492. bp.addAssign( 0.14 );
  19493. } );
  19494. return rz;
  19495. } ).setLayout( {
  19496. name: 'triNoise3D',
  19497. type: 'float',
  19498. inputs: [
  19499. { name: 'position', type: 'vec3' },
  19500. { name: 'speed', type: 'float' },
  19501. { name: 'time', type: 'float' }
  19502. ]
  19503. } );
  19504. /** @module FunctionOverloadingNode **/
  19505. /**
  19506. * This class allows to define multiple overloaded versions
  19507. * of the same function. Depending on the parameters of the function
  19508. * call, the node picks the best-fit overloaded version.
  19509. *
  19510. * @augments Node
  19511. */
  19512. class FunctionOverloadingNode extends Node {
  19513. static get type() {
  19514. return 'FunctionOverloadingNode';
  19515. }
  19516. /**
  19517. * Constructs a new function overloading node.
  19518. *
  19519. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19520. * @param {...Node} parametersNodes - A list of parameter nodes.
  19521. */
  19522. constructor( functionNodes = [], ...parametersNodes ) {
  19523. super();
  19524. /**
  19525. * Array of `Fn` function definitions.
  19526. *
  19527. * @type {Array<Function>}
  19528. */
  19529. this.functionNodes = functionNodes;
  19530. /**
  19531. * A list of parameter nodes.
  19532. *
  19533. * @type {Array<Node>}
  19534. */
  19535. this.parametersNodes = parametersNodes;
  19536. /**
  19537. * The selected overloaded function call.
  19538. *
  19539. * @private
  19540. * @type {ShaderCallNodeInternal}
  19541. */
  19542. this._candidateFnCall = null;
  19543. /**
  19544. * This node is marked as global.
  19545. *
  19546. * @type {Boolean}
  19547. * @default true
  19548. */
  19549. this.global = true;
  19550. }
  19551. /**
  19552. * This method is overwritten since the node type is inferred from
  19553. * the function's return type.
  19554. *
  19555. * @param {NodeBuilder} builder - The current node builder.
  19556. * @return {String} The node type.
  19557. */
  19558. getNodeType() {
  19559. return this.functionNodes[ 0 ].shaderNode.layout.type;
  19560. }
  19561. setup( builder ) {
  19562. const params = this.parametersNodes;
  19563. let candidateFnCall = this._candidateFnCall;
  19564. if ( candidateFnCall === null ) {
  19565. let candidateFn = null;
  19566. let candidateScore = - 1;
  19567. for ( const functionNode of this.functionNodes ) {
  19568. const shaderNode = functionNode.shaderNode;
  19569. const layout = shaderNode.layout;
  19570. if ( layout === null ) {
  19571. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  19572. }
  19573. const inputs = layout.inputs;
  19574. if ( params.length === inputs.length ) {
  19575. let score = 0;
  19576. for ( let i = 0; i < params.length; i ++ ) {
  19577. const param = params[ i ];
  19578. const input = inputs[ i ];
  19579. if ( param.getNodeType( builder ) === input.type ) {
  19580. score ++;
  19581. } else {
  19582. score = 0;
  19583. }
  19584. }
  19585. if ( score > candidateScore ) {
  19586. candidateFn = functionNode;
  19587. candidateScore = score;
  19588. }
  19589. }
  19590. }
  19591. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  19592. }
  19593. return candidateFnCall;
  19594. }
  19595. }
  19596. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  19597. /**
  19598. * TSL function for creating a function overloading node.
  19599. *
  19600. * @function
  19601. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  19602. * @returns {FunctionOverloadingNode}
  19603. */
  19604. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  19605. /** @module Timer **/
  19606. /**
  19607. * Represents the elapsed time in seconds.
  19608. *
  19609. * @type {UniformNode<float>}
  19610. */
  19611. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  19612. /**
  19613. * Represents the delta time in seconds.
  19614. *
  19615. * @type {UniformNode<float>}
  19616. */
  19617. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  19618. /**
  19619. * Represents the current frame ID.
  19620. *
  19621. * @type {UniformNode<uint>}
  19622. */
  19623. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  19624. // Deprecated
  19625. /**
  19626. * @function
  19627. * @deprecated since r170. Use {@link time} instead.
  19628. *
  19629. * @param {Number} [timeScale=1] - The time scale.
  19630. * @returns {UniformNode<float>}
  19631. */
  19632. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  19633. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  19634. return time.mul( timeScale );
  19635. };
  19636. /**
  19637. * @function
  19638. * @deprecated since r170. Use {@link time} instead.
  19639. *
  19640. * @param {Number} [timeScale=1] - The time scale.
  19641. * @returns {UniformNode<float>}
  19642. */
  19643. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  19644. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  19645. return time.mul( timeScale );
  19646. };
  19647. /**
  19648. * @function
  19649. * @deprecated since r170. Use {@link deltaTime} instead.
  19650. *
  19651. * @param {Number} [timeScale=1] - The time scale.
  19652. * @returns {UniformNode<float>}
  19653. */
  19654. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  19655. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  19656. return deltaTime.mul( timeScale );
  19657. };
  19658. /** @module Oscillators **/
  19659. /**
  19660. * Generates a sine wave oscillation based on a timer.
  19661. *
  19662. * @method
  19663. * @param {Node<float>} t - The timer to generate the oscillation with.
  19664. * @return {Node<float>} The oscillation node.
  19665. */
  19666. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  19667. /**
  19668. * Generates a square wave oscillation based on a timer.
  19669. *
  19670. * @method
  19671. * @param {Node<float>} t - The timer to generate the oscillation with.
  19672. * @return {Node<float>} The oscillation node.
  19673. */
  19674. const oscSquare = ( t = time ) => t.fract().round();
  19675. /**
  19676. * Generates a triangle wave oscillation based on a timer.
  19677. *
  19678. * @method
  19679. * @param {Node<float>} t - The timer to generate the oscillation with.
  19680. * @return {Node<float>} The oscillation node.
  19681. */
  19682. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  19683. /**
  19684. * Generates a sawtooth wave oscillation based on a timer.
  19685. *
  19686. * @method
  19687. * @param {Node<float>} t - The timer to generate the oscillation with.
  19688. * @return {Node<float>} The oscillation node.
  19689. */
  19690. const oscSawtooth = ( t = time ) => t.fract();
  19691. /** @module UVUtils **/
  19692. /**
  19693. * Rotates the given uv coordinates around a center point
  19694. *
  19695. * @method
  19696. * @param {Node<vec2>} uv - The uv coordinates.
  19697. * @param {Node<float>} rotation - The rotation defined in radians.
  19698. * @param {Node<vec2>} center - The center of rotation
  19699. * @return {Node<vec2>} The rotated uv coordinates.
  19700. */
  19701. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  19702. return rotate( uv.sub( center ), rotation ).add( center );
  19703. } );
  19704. /**
  19705. * Applies a spherical warping effect to the given uv coordinates.
  19706. *
  19707. * @method
  19708. * @param {Node<vec2>} uv - The uv coordinates.
  19709. * @param {Node<float>} strength - The strength of the effect.
  19710. * @param {Node<vec2>} center - The center point
  19711. * @return {Node<vec2>} The updated uv coordinates.
  19712. */
  19713. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  19714. const delta = uv.sub( center );
  19715. const delta2 = delta.dot( delta );
  19716. const delta4 = delta2.mul( delta2 );
  19717. const deltaOffset = delta4.mul( strength );
  19718. return uv.add( delta.mul( deltaOffset ) );
  19719. } );
  19720. /** @module SpriteUtils **/
  19721. /**
  19722. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  19723. * oriented always towards the camera.
  19724. *
  19725. * ```js
  19726. * material.vertexNode = billboarding();
  19727. * ```
  19728. *
  19729. * @method
  19730. * @param {Object} config - The configuration object.
  19731. * @param {Node<vec3>?} [config.position=null] - Can be used to define the vertex positions in world space.
  19732. * @param {Boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  19733. * @param {Boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  19734. * @return {Node<vec3>} The updated vertex position in clip space.
  19735. */
  19736. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  19737. let worldMatrix;
  19738. if ( position !== null ) {
  19739. worldMatrix = modelWorldMatrix.toVar();
  19740. worldMatrix[ 3 ][ 0 ] = position.x;
  19741. worldMatrix[ 3 ][ 1 ] = position.y;
  19742. worldMatrix[ 3 ][ 2 ] = position.z;
  19743. } else {
  19744. worldMatrix = modelWorldMatrix;
  19745. }
  19746. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  19747. if ( defined( horizontal ) ) {
  19748. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  19749. modelViewMatrix[ 0 ][ 1 ] = 0;
  19750. modelViewMatrix[ 0 ][ 2 ] = 0;
  19751. }
  19752. if ( defined( vertical ) ) {
  19753. modelViewMatrix[ 1 ][ 0 ] = 0;
  19754. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  19755. modelViewMatrix[ 1 ][ 2 ] = 0;
  19756. }
  19757. modelViewMatrix[ 2 ][ 0 ] = 0;
  19758. modelViewMatrix[ 2 ][ 1 ] = 0;
  19759. modelViewMatrix[ 2 ][ 2 ] = 1;
  19760. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  19761. } );
  19762. /** @module ViewportUtils **/
  19763. /**
  19764. * A special version of a screen uv function that involves a depth comparison
  19765. * when computing the final uvs. The function mitigates visual errors when
  19766. * using viewport texture nodes for refraction purposes. Without this function
  19767. * objects in front of a refractive surface might appear on the refractive surface
  19768. * which is incorrect.
  19769. *
  19770. * @method
  19771. * @param {Node<vec2>?} uv - Optional uv coordinates. By default `screenUV` is used.
  19772. * @return {Node<vec2>} The update uv coordinates.
  19773. */
  19774. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  19775. const depth = linearDepth();
  19776. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  19777. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  19778. return finalUV;
  19779. } );
  19780. /** @module SpriteSheetUVNode **/
  19781. /**
  19782. * Can be used to compute texture coordinates for animated sprite sheets.
  19783. *
  19784. * ```js
  19785. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  19786. *
  19787. * material.colorNode = texture( spriteSheet, uvNode );
  19788. * ```
  19789. *
  19790. * @augments Node
  19791. */
  19792. class SpriteSheetUVNode extends Node {
  19793. static get type() {
  19794. return 'SpriteSheetUVNode';
  19795. }
  19796. /**
  19797. * Constructs a new sprite sheet uv node.
  19798. *
  19799. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19800. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19801. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19802. */
  19803. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  19804. super( 'vec2' );
  19805. /**
  19806. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19807. *
  19808. * @type {Node<vec2>}
  19809. */
  19810. this.countNode = countNode;
  19811. /**
  19812. * The uv node.
  19813. *
  19814. * @type {Node<vec2>}
  19815. */
  19816. this.uvNode = uvNode;
  19817. /**
  19818. * The node that defines the current frame/sprite.
  19819. *
  19820. * @type {Node<float>}
  19821. */
  19822. this.frameNode = frameNode;
  19823. }
  19824. setup() {
  19825. const { frameNode, uvNode, countNode } = this;
  19826. const { width, height } = countNode;
  19827. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  19828. const column = frameNum.mod( width );
  19829. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  19830. const scale = countNode.reciprocal();
  19831. const uvFrameOffset = vec2( column, row );
  19832. return uvNode.add( uvFrameOffset ).mul( scale );
  19833. }
  19834. }
  19835. /**
  19836. * TSL function for creating a sprite sheet uv node.
  19837. *
  19838. * @function
  19839. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  19840. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  19841. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  19842. * @returns {SpriteSheetUVNode}
  19843. */
  19844. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode );
  19845. /** @module TriplanarTexturesNode **/
  19846. /**
  19847. * Can be used for triplanar texture mapping.
  19848. *
  19849. * ```js
  19850. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  19851. * ```
  19852. *
  19853. * @augments Node
  19854. */
  19855. class TriplanarTexturesNode extends Node {
  19856. static get type() {
  19857. return 'TriplanarTexturesNode';
  19858. }
  19859. /**
  19860. * Constructs a new triplanar textures node.
  19861. *
  19862. * @param {Node} textureXNode - First texture node.
  19863. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19864. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19865. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19866. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19867. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19868. */
  19869. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  19870. super( 'vec4' );
  19871. /**
  19872. * First texture node.
  19873. *
  19874. * @type {Node}
  19875. */
  19876. this.textureXNode = textureXNode;
  19877. /**
  19878. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19879. *
  19880. * @type {Node}
  19881. * @default null
  19882. */
  19883. this.textureYNode = textureYNode;
  19884. /**
  19885. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19886. *
  19887. * @type {Node}
  19888. * @default null
  19889. */
  19890. this.textureZNode = textureZNode;
  19891. /**
  19892. * The scale node.
  19893. *
  19894. * @type {Node<float>}
  19895. * @default float(1)
  19896. */
  19897. this.scaleNode = scaleNode;
  19898. /**
  19899. * Vertex positions in local space.
  19900. *
  19901. * @type {Node<vec3>}
  19902. * @default positionLocal
  19903. */
  19904. this.positionNode = positionNode;
  19905. /**
  19906. * Normals in local space.
  19907. *
  19908. * @type {Node<vec3>}
  19909. * @default normalLocal
  19910. */
  19911. this.normalNode = normalNode;
  19912. }
  19913. setup() {
  19914. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  19915. // Ref: https://github.com/keijiro/StandardTriplanar
  19916. // Blending factor of triplanar mapping
  19917. let bf = normalNode.abs().normalize();
  19918. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  19919. // Triplanar mapping
  19920. const tx = positionNode.yz.mul( scaleNode );
  19921. const ty = positionNode.zx.mul( scaleNode );
  19922. const tz = positionNode.xy.mul( scaleNode );
  19923. // Base color
  19924. const textureX = textureXNode.value;
  19925. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  19926. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  19927. const cx = texture( textureX, tx ).mul( bf.x );
  19928. const cy = texture( textureY, ty ).mul( bf.y );
  19929. const cz = texture( textureZ, tz ).mul( bf.z );
  19930. return add( cx, cy, cz );
  19931. }
  19932. }
  19933. /**
  19934. * TSL function for creating a triplanar textures node.
  19935. *
  19936. * @function
  19937. * @param {Node} textureXNode - First texture node.
  19938. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19939. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19940. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19941. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19942. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19943. * @returns {TriplanarTexturesNode}
  19944. */
  19945. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode );
  19946. /**
  19947. * TSL function for creating a triplanar textures node.
  19948. *
  19949. * @function
  19950. * @param {Node} textureXNode - First texture node.
  19951. * @param {Node?} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  19952. * @param {Node?} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  19953. * @param {Node<float>?} [scaleNode=float(1)] - The scale node.
  19954. * @param {Node<vec3>?} [positionNode=positionLocal] - Vertex positions in local space.
  19955. * @param {Node<vec3>?} [normalNode=normalLocal] - Normals in local space.
  19956. * @returns {TriplanarTexturesNode}
  19957. */
  19958. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  19959. /** @module ReflectorNode **/
  19960. const _reflectorPlane = new Plane();
  19961. const _normal = new Vector3();
  19962. const _reflectorWorldPosition = new Vector3();
  19963. const _cameraWorldPosition = new Vector3();
  19964. const _rotationMatrix = new Matrix4();
  19965. const _lookAtPosition = new Vector3( 0, 0, - 1 );
  19966. const clipPlane = new Vector4();
  19967. const _view = new Vector3();
  19968. const _target = new Vector3();
  19969. const _q = new Vector4();
  19970. const _size$2 = new Vector2();
  19971. const _defaultRT = new RenderTarget();
  19972. const _defaultUV = screenUV.flipX();
  19973. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  19974. let _inReflector = false;
  19975. /**
  19976. * This node can be used to implement mirror-like flat reflective surfaces.
  19977. *
  19978. * ```js
  19979. * const groundReflector = reflector();
  19980. * material.colorNode = groundReflector;
  19981. *
  19982. * const plane = new Mesh( geometry, material );
  19983. * plane.add( groundReflector.target );
  19984. * ```
  19985. *
  19986. * @augments module:TextureNode~TextureNode
  19987. */
  19988. class ReflectorNode extends TextureNode {
  19989. static get type() {
  19990. return 'ReflectorNode';
  19991. }
  19992. /**
  19993. * Constructs a new reflector node.
  19994. *
  19995. * @param {Object} [parameters={}] - An object holding configuration parameters.
  19996. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  19997. * @param {Number} [parameters.resolution=1] - The resolution scale.
  19998. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  19999. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20000. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20001. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20002. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20003. */
  20004. constructor( parameters = {} ) {
  20005. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  20006. /**
  20007. * A reference to the internal reflector base node which holds the actual implementation.
  20008. *
  20009. * @private
  20010. * @type {ReflectorBaseNode?}
  20011. * @default null
  20012. */
  20013. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  20014. /**
  20015. * A reference to the internal depth node.
  20016. *
  20017. * @private
  20018. * @type {Node?}
  20019. * @default null
  20020. */
  20021. this._depthNode = null;
  20022. this.setUpdateMatrix( false );
  20023. }
  20024. /**
  20025. * A reference to the internal reflector node.
  20026. *
  20027. * @type {ReflectorBaseNode}
  20028. */
  20029. get reflector() {
  20030. return this._reflectorBaseNode;
  20031. }
  20032. /**
  20033. * A reference to 3D object the reflector is linked to.
  20034. *
  20035. * @type {Object3D}
  20036. */
  20037. get target() {
  20038. return this._reflectorBaseNode.target;
  20039. }
  20040. /**
  20041. * Returns a node representing the mirror's depth. That can be used
  20042. * to implement more advanced reflection effects like distance attenuation.
  20043. *
  20044. * @return {Node} The depth node.
  20045. */
  20046. getDepthNode() {
  20047. if ( this._depthNode === null ) {
  20048. if ( this._reflectorBaseNode.depth !== true ) {
  20049. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  20050. }
  20051. this._depthNode = nodeObject( new ReflectorNode( {
  20052. defaultTexture: _defaultRT.depthTexture,
  20053. reflector: this._reflectorBaseNode
  20054. } ) );
  20055. }
  20056. return this._depthNode;
  20057. }
  20058. setup( builder ) {
  20059. // ignore if used in post-processing
  20060. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  20061. return super.setup( builder );
  20062. }
  20063. clone() {
  20064. const texture = new this.constructor( this.reflectorNode );
  20065. texture._reflectorBaseNode = this._reflectorBaseNode;
  20066. return texture;
  20067. }
  20068. }
  20069. /**
  20070. * Holds the actual implementation of the reflector.
  20071. *
  20072. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  20073. * in `ReflectorNode`, see #29619.
  20074. *
  20075. * @private
  20076. * @augments Node
  20077. */
  20078. class ReflectorBaseNode extends Node {
  20079. static get type() {
  20080. return 'ReflectorBaseNode';
  20081. }
  20082. /**
  20083. * Constructs a new reflector base node.
  20084. *
  20085. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  20086. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20087. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20088. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20089. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20090. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20091. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20092. */
  20093. constructor( textureNode, parameters = {} ) {
  20094. super();
  20095. const {
  20096. target = new Object3D(),
  20097. resolution = 1,
  20098. generateMipmaps = false,
  20099. bounces = true,
  20100. depth = false
  20101. } = parameters;
  20102. /**
  20103. * Represents the rendered reflections as a texture node.
  20104. *
  20105. * @type {TextureNode}
  20106. */
  20107. this.textureNode = textureNode;
  20108. /**
  20109. * The 3D object the reflector is linked to.
  20110. *
  20111. * @type {Object3D}
  20112. * @default {new Object3D()}
  20113. */
  20114. this.target = target;
  20115. /**
  20116. * The resolution scale.
  20117. *
  20118. * @type {Number}
  20119. * @default {1}
  20120. */
  20121. this.resolution = resolution;
  20122. /**
  20123. * Whether mipmaps should be generated or not.
  20124. *
  20125. * @type {Boolean}
  20126. * @default {false}
  20127. */
  20128. this.generateMipmaps = generateMipmaps;
  20129. /**
  20130. * Whether reflectors can render other reflector nodes or not.
  20131. *
  20132. * @type {Boolean}
  20133. * @default {true}
  20134. */
  20135. this.bounces = bounces;
  20136. /**
  20137. * Whether depth data should be generated or not.
  20138. *
  20139. * @type {Boolean}
  20140. * @default {false}
  20141. */
  20142. this.depth = depth;
  20143. /**
  20144. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  20145. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  20146. *
  20147. * @type {String}
  20148. * @default 'render'
  20149. */
  20150. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  20151. /**
  20152. * Weak map for managing virtual cameras.
  20153. *
  20154. * @type {WeakMap<Camera, Camera>}
  20155. */
  20156. this.virtualCameras = new WeakMap();
  20157. /**
  20158. * Weak map for managing render targets.
  20159. *
  20160. * @type {WeakMap<Camera, RenderTarget>}
  20161. */
  20162. this.renderTargets = new WeakMap();
  20163. }
  20164. /**
  20165. * Updates the resolution of the internal render target.
  20166. *
  20167. * @private
  20168. * @param {RenderTarget} renderTarget - The render target to resize.
  20169. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  20170. */
  20171. _updateResolution( renderTarget, renderer ) {
  20172. const resolution = this.resolution;
  20173. renderer.getDrawingBufferSize( _size$2 );
  20174. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  20175. }
  20176. setup( builder ) {
  20177. this._updateResolution( _defaultRT, builder.renderer );
  20178. return super.setup( builder );
  20179. }
  20180. /**
  20181. * Returns a virtual camera for the given camera. The virtual camera is used to
  20182. * render the scene from the reflector's view so correct reflections can be produced.
  20183. *
  20184. * @param {Camera} camera - The scene's camera.
  20185. * @return {Camera} The corresponding virtual camera.
  20186. */
  20187. getVirtualCamera( camera ) {
  20188. let virtualCamera = this.virtualCameras.get( camera );
  20189. if ( virtualCamera === undefined ) {
  20190. virtualCamera = camera.clone();
  20191. this.virtualCameras.set( camera, virtualCamera );
  20192. }
  20193. return virtualCamera;
  20194. }
  20195. /**
  20196. * Returns a render target for the given camera. The reflections are rendered
  20197. * into this render target.
  20198. *
  20199. * @param {Camera} camera - The scene's camera.
  20200. * @return {RenderTarget} The render target.
  20201. */
  20202. getRenderTarget( camera ) {
  20203. let renderTarget = this.renderTargets.get( camera );
  20204. if ( renderTarget === undefined ) {
  20205. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  20206. if ( this.generateMipmaps === true ) {
  20207. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  20208. renderTarget.texture.generateMipmaps = true;
  20209. }
  20210. if ( this.depth === true ) {
  20211. renderTarget.depthTexture = new DepthTexture();
  20212. }
  20213. this.renderTargets.set( camera, renderTarget );
  20214. }
  20215. return renderTarget;
  20216. }
  20217. updateBefore( frame ) {
  20218. if ( this.bounces === false && _inReflector ) return false;
  20219. _inReflector = true;
  20220. const { scene, camera, renderer, material } = frame;
  20221. const { target } = this;
  20222. const virtualCamera = this.getVirtualCamera( camera );
  20223. const renderTarget = this.getRenderTarget( virtualCamera );
  20224. renderer.getDrawingBufferSize( _size$2 );
  20225. this._updateResolution( renderTarget, renderer );
  20226. //
  20227. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  20228. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  20229. _rotationMatrix.extractRotation( target.matrixWorld );
  20230. _normal.set( 0, 0, 1 );
  20231. _normal.applyMatrix4( _rotationMatrix );
  20232. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  20233. // Avoid rendering when reflector is facing away
  20234. if ( _view.dot( _normal ) > 0 ) return;
  20235. _view.reflect( _normal ).negate();
  20236. _view.add( _reflectorWorldPosition );
  20237. _rotationMatrix.extractRotation( camera.matrixWorld );
  20238. _lookAtPosition.set( 0, 0, - 1 );
  20239. _lookAtPosition.applyMatrix4( _rotationMatrix );
  20240. _lookAtPosition.add( _cameraWorldPosition );
  20241. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  20242. _target.reflect( _normal ).negate();
  20243. _target.add( _reflectorWorldPosition );
  20244. //
  20245. virtualCamera.coordinateSystem = camera.coordinateSystem;
  20246. virtualCamera.position.copy( _view );
  20247. virtualCamera.up.set( 0, 1, 0 );
  20248. virtualCamera.up.applyMatrix4( _rotationMatrix );
  20249. virtualCamera.up.reflect( _normal );
  20250. virtualCamera.lookAt( _target );
  20251. virtualCamera.near = camera.near;
  20252. virtualCamera.far = camera.far;
  20253. virtualCamera.updateMatrixWorld();
  20254. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  20255. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  20256. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  20257. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  20258. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  20259. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  20260. const projectionMatrix = virtualCamera.projectionMatrix;
  20261. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  20262. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  20263. _q.z = - 1.0;
  20264. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  20265. // Calculate the scaled plane vector
  20266. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  20267. const clipBias = 0;
  20268. // Replacing the third row of the projection matrix
  20269. projectionMatrix.elements[ 2 ] = clipPlane.x;
  20270. projectionMatrix.elements[ 6 ] = clipPlane.y;
  20271. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  20272. projectionMatrix.elements[ 14 ] = clipPlane.w;
  20273. //
  20274. this.textureNode.value = renderTarget.texture;
  20275. if ( this.depth === true ) {
  20276. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  20277. }
  20278. material.visible = false;
  20279. const currentRenderTarget = renderer.getRenderTarget();
  20280. const currentMRT = renderer.getMRT();
  20281. const currentAutoClear = renderer.autoClear;
  20282. renderer.setMRT( null );
  20283. renderer.setRenderTarget( renderTarget );
  20284. renderer.autoClear = true;
  20285. renderer.render( scene, virtualCamera );
  20286. renderer.setMRT( currentMRT );
  20287. renderer.setRenderTarget( currentRenderTarget );
  20288. renderer.autoClear = currentAutoClear;
  20289. material.visible = true;
  20290. _inReflector = false;
  20291. }
  20292. }
  20293. /**
  20294. * TSL function for creating a reflector node.
  20295. *
  20296. * @function
  20297. * @param {Object} [parameters={}] - An object holding configuration parameters.
  20298. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  20299. * @param {Number} [parameters.resolution=1] - The resolution scale.
  20300. * @param {Boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  20301. * @param {Boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  20302. * @param {Boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  20303. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  20304. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  20305. * @returns {ReflectorNode}
  20306. */
  20307. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  20308. const _camera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  20309. /**
  20310. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  20311. *
  20312. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  20313. *
  20314. * @private
  20315. * @augments BufferGeometry
  20316. */
  20317. class QuadGeometry extends BufferGeometry {
  20318. /**
  20319. * Constructs a new quad geometry.
  20320. *
  20321. * @param {Boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  20322. */
  20323. constructor( flipY = false ) {
  20324. super();
  20325. const uv = flipY === false ? [ 0, - 1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  20326. this.setAttribute( 'position', new Float32BufferAttribute( [ - 1, 3, 0, - 1, - 1, 0, 3, - 1, 0 ], 3 ) );
  20327. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  20328. }
  20329. }
  20330. const _geometry = /*@__PURE__*/ new QuadGeometry();
  20331. /**
  20332. * This module is a helper for passes which need to render a full
  20333. * screen effect which is quite common in context of post processing.
  20334. *
  20335. * The intended usage is to reuse a single quad mesh for rendering
  20336. * subsequent passes by just reassigning the `material` reference.
  20337. *
  20338. * @augments Mesh
  20339. */
  20340. class QuadMesh extends Mesh {
  20341. /**
  20342. * Constructs a new quad mesh.
  20343. *
  20344. * @param {Material?} [material=null] - The material to render the quad mesh with.
  20345. */
  20346. constructor( material = null ) {
  20347. super( _geometry, material );
  20348. /**
  20349. * The camera to render the quad mesh with.
  20350. *
  20351. * @type {OrthographicCamera}
  20352. * @readonly
  20353. */
  20354. this.camera = _camera;
  20355. /**
  20356. * This flag can be used for type testing.
  20357. *
  20358. * @type {Boolean}
  20359. * @readonly
  20360. * @default true
  20361. */
  20362. this.isQuadMesh = true;
  20363. }
  20364. /**
  20365. * Async version of `render()`.
  20366. *
  20367. * @async
  20368. * @param {Renderer} renderer - The renderer.
  20369. * @return {Promise} A Promise that resolves when the render has been finished.
  20370. */
  20371. async renderAsync( renderer ) {
  20372. return renderer.renderAsync( this, _camera );
  20373. }
  20374. /**
  20375. * Renders the quad mesh
  20376. *
  20377. * @param {Renderer} renderer - The renderer.
  20378. */
  20379. render( renderer ) {
  20380. renderer.render( this, _camera );
  20381. }
  20382. }
  20383. /** @module RTTNode **/
  20384. const _size$1 = /*@__PURE__*/ new Vector2();
  20385. /**
  20386. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  20387. * This module is especially relevant in context of post processing where certain nodes require
  20388. * texture input for their effects. With the helper function `convertToTexture()` which is based
  20389. * on this module, the node system can automatically ensure texture input if required.
  20390. *
  20391. * @augments module:TextureNode~TextureNode
  20392. */
  20393. class RTTNode extends TextureNode {
  20394. static get type() {
  20395. return 'RTTNode';
  20396. }
  20397. /**
  20398. * Constructs a new RTT node.
  20399. *
  20400. * @param {Node} node - The node to render a texture with.
  20401. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20402. * @param {Number?} [height=null] - The height of the internal render target.
  20403. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20404. */
  20405. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  20406. const renderTarget = new RenderTarget( width, height, options );
  20407. super( renderTarget.texture, uv() );
  20408. /**
  20409. * The node to render a texture with.
  20410. *
  20411. * @type {Node}
  20412. */
  20413. this.node = node;
  20414. /**
  20415. * The width of the internal render target.
  20416. * If not width is applied, the render target is automatically resized.
  20417. *
  20418. * @type {Number?}
  20419. * @default null
  20420. */
  20421. this.width = width;
  20422. /**
  20423. * The height of the internal render target.
  20424. *
  20425. * @type {Number?}
  20426. * @default null
  20427. */
  20428. this.height = height;
  20429. /**
  20430. * The pixel ratio
  20431. *
  20432. * @type {Number}
  20433. * @default 1
  20434. */
  20435. this.pixelRatio = 1;
  20436. /**
  20437. * The render target
  20438. *
  20439. * @type {RenderTarget}
  20440. */
  20441. this.renderTarget = renderTarget;
  20442. /**
  20443. * Whether the texture requires an update or not.
  20444. *
  20445. * @type {Boolean}
  20446. * @default true
  20447. */
  20448. this.textureNeedsUpdate = true;
  20449. /**
  20450. * Whether the texture should automatically be updated or not.
  20451. *
  20452. * @type {Boolean}
  20453. * @default true
  20454. */
  20455. this.autoUpdate = true;
  20456. /**
  20457. * The node which is used with the quad mesh for RTT.
  20458. *
  20459. * @private
  20460. * @type {Node}
  20461. * @default null
  20462. */
  20463. this._rttNode = null;
  20464. /**
  20465. * The internal quad mesh for RTT.
  20466. *
  20467. * @private
  20468. * @type {QuadMesh}
  20469. */
  20470. this._quadMesh = new QuadMesh( new NodeMaterial() );
  20471. /**
  20472. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  20473. * the texture once per render in its {@link RTTNode#updateBefore} method.
  20474. *
  20475. * @type {String}
  20476. * @default 'render'
  20477. */
  20478. this.updateBeforeType = NodeUpdateType.RENDER;
  20479. }
  20480. /**
  20481. * Whether the internal render target should automatically be resized or not.
  20482. *
  20483. * @type {Boolean}
  20484. * @readonly
  20485. * @default true
  20486. */
  20487. get autoSize() {
  20488. return this.width === null;
  20489. }
  20490. setup( builder ) {
  20491. this._rttNode = this.node.context( builder.getSharedContext() );
  20492. this._quadMesh.material.name = 'RTT';
  20493. this._quadMesh.material.needsUpdate = true;
  20494. return super.setup( builder );
  20495. }
  20496. /**
  20497. * Sets the size of the internal render target
  20498. *
  20499. * @param {Number} width - The width to set.
  20500. * @param {Number} height - The width to set.
  20501. */
  20502. setSize( width, height ) {
  20503. this.width = width;
  20504. this.height = height;
  20505. const effectiveWidth = width * this.pixelRatio;
  20506. const effectiveHeight = height * this.pixelRatio;
  20507. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  20508. this.textureNeedsUpdate = true;
  20509. }
  20510. /**
  20511. * Sets the pixel ratio. This will also resize the render target.
  20512. *
  20513. * @param {Number} pixelRatio - The pixel ratio to set.
  20514. */
  20515. setPixelRatio( pixelRatio ) {
  20516. this.pixelRatio = pixelRatio;
  20517. this.setSize( this.width, this.height );
  20518. }
  20519. updateBefore( { renderer } ) {
  20520. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  20521. this.textureNeedsUpdate = false;
  20522. //
  20523. if ( this.autoSize === true ) {
  20524. this.pixelRatio = renderer.getPixelRatio();
  20525. const size = renderer.getSize( _size$1 );
  20526. this.setSize( size.width, size.height );
  20527. }
  20528. //
  20529. this._quadMesh.material.fragmentNode = this._rttNode;
  20530. //
  20531. const currentRenderTarget = renderer.getRenderTarget();
  20532. renderer.setRenderTarget( this.renderTarget );
  20533. this._quadMesh.render( renderer );
  20534. renderer.setRenderTarget( currentRenderTarget );
  20535. }
  20536. clone() {
  20537. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  20538. newNode.sampler = this.sampler;
  20539. newNode.referenceNode = this;
  20540. return newNode;
  20541. }
  20542. }
  20543. /**
  20544. * TSL function for creating a RTT node.
  20545. *
  20546. * @function
  20547. * @param {Node} node - The node to render a texture with.
  20548. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20549. * @param {Number?} [height=null] - The height of the internal render target.
  20550. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20551. * @returns {RTTNode}
  20552. */
  20553. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  20554. /**
  20555. * TSL function for converting nodes to textures nodes.
  20556. *
  20557. * @function
  20558. * @param {Node} node - The node to render a texture with.
  20559. * @param {Number?} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  20560. * @param {Number?} [height=null] - The height of the internal render target.
  20561. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  20562. * @returns {RTTNode}
  20563. */
  20564. const convertToTexture = ( node, ...params ) => {
  20565. if ( node.isTextureNode ) return node;
  20566. if ( node.isPassNode ) return node.getTextureNode();
  20567. return rtt( node, ...params );
  20568. };
  20569. /** @module PostProcessingUtils **/
  20570. /**
  20571. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  20572. * depth value and the camera's inverse projection matrix.
  20573. *
  20574. * @method
  20575. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  20576. * @param {Node<float>} depth - The fragment's depth value.
  20577. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20578. * @return {Node<vec3>} The fragments position in view space.
  20579. */
  20580. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  20581. let clipSpacePosition;
  20582. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  20583. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  20584. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  20585. } else {
  20586. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  20587. }
  20588. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  20589. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  20590. } );
  20591. /**
  20592. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  20593. * and the camera's projection matrix
  20594. *
  20595. * @method
  20596. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  20597. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  20598. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  20599. */
  20600. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  20601. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  20602. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  20603. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  20604. } );
  20605. /**
  20606. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  20607. * target is available or if flat surface normals are required.
  20608. *
  20609. * @method
  20610. * @param {Node<vec2>} uv - The texture coordinate.
  20611. * @param {DepthTexture} depthTexture - The depth texture.
  20612. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  20613. * @return {Node<vec3>} The computed normal vector.
  20614. */
  20615. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  20616. const size = textureSize( textureLoad( depthTexture ) );
  20617. const p = ivec2( uv.mul( size ) ).toVar();
  20618. const c0 = textureLoad( depthTexture, p ).toVar();
  20619. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  20620. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  20621. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  20622. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  20623. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  20624. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  20625. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  20626. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  20627. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  20628. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  20629. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  20630. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  20631. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  20632. 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 ) ) );
  20633. 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 ) ) );
  20634. return normalize( cross( dpdx, dpdy ) );
  20635. } );
  20636. /**
  20637. * This special type of instanced buffer attribute is intended for compute shaders.
  20638. * In earlier three.js versions it was only possible to update attribute data
  20639. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20640. * new material system and renderer it is now possible to use compute shaders
  20641. * to compute the data for an attribute more efficiently on the GPU.
  20642. *
  20643. * The idea is to create an instance of this class and provide it as an input
  20644. * to {@link module:StorageBufferNode}.
  20645. *
  20646. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20647. *
  20648. * @augments InstancedBufferAttribute
  20649. */
  20650. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  20651. /**
  20652. * Constructs a new storage instanced buffer attribute.
  20653. *
  20654. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20655. * The subsequent parameters are then obsolete.
  20656. * @param {Number} itemSize - The item size.
  20657. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20658. */
  20659. constructor( count, itemSize, typeClass = Float32Array ) {
  20660. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20661. super( array, itemSize );
  20662. /**
  20663. * This flag can be used for type testing.
  20664. *
  20665. * @type {Boolean}
  20666. * @readonly
  20667. * @default true
  20668. */
  20669. this.isStorageInstancedBufferAttribute = true;
  20670. }
  20671. }
  20672. /**
  20673. * This special type of buffer attribute is intended for compute shaders.
  20674. * In earlier three.js versions it was only possible to update attribute data
  20675. * on the CPU via JavaScript and then upload the data to the GPU. With the
  20676. * new material system and renderer it is now possible to use compute shaders
  20677. * to compute the data for an attribute more efficiently on the GPU.
  20678. *
  20679. * The idea is to create an instance of this class and provide it as an input
  20680. * to {@link module:StorageBufferNode}.
  20681. *
  20682. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  20683. *
  20684. * @augments BufferAttribute
  20685. */
  20686. class StorageBufferAttribute extends BufferAttribute {
  20687. /**
  20688. * Constructs a new storage buffer attribute.
  20689. *
  20690. * @param {Number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  20691. * The subsequent parameters are then obsolete.
  20692. * @param {Number} itemSize - The item size.
  20693. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  20694. */
  20695. constructor( count, itemSize, typeClass = Float32Array ) {
  20696. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  20697. super( array, itemSize );
  20698. /**
  20699. * This flag can be used for type testing.
  20700. *
  20701. * @type {Boolean}
  20702. * @readonly
  20703. * @default true
  20704. */
  20705. this.isStorageBufferAttribute = true;
  20706. }
  20707. }
  20708. /** @module StorageArrayElementNode **/
  20709. /**
  20710. * This class enables element access on instances of {@link StorageBufferNode}.
  20711. * In most cases, it is indirectly used when accessing elements with the
  20712. * {@link StorageBufferNode#element} method.
  20713. *
  20714. * ```js
  20715. * const position = positionStorage.element( instanceIndex );
  20716. * ```
  20717. *
  20718. * @augments ArrayElementNode
  20719. */
  20720. class StorageArrayElementNode extends ArrayElementNode {
  20721. static get type() {
  20722. return 'StorageArrayElementNode';
  20723. }
  20724. /**
  20725. * Constructs storage buffer element node.
  20726. *
  20727. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20728. * @param {Node} indexNode - The index node that defines the element access.
  20729. */
  20730. constructor( storageBufferNode, indexNode ) {
  20731. super( storageBufferNode, indexNode );
  20732. /**
  20733. * This flag can be used for type testing.
  20734. *
  20735. * @type {Boolean}
  20736. * @readonly
  20737. * @default true
  20738. */
  20739. this.isStorageArrayElementNode = true;
  20740. }
  20741. /**
  20742. * The storage buffer node.
  20743. *
  20744. * @param {Node} value
  20745. * @type {StorageBufferNode}
  20746. */
  20747. set storageBufferNode( value ) {
  20748. this.node = value;
  20749. }
  20750. get storageBufferNode() {
  20751. return this.node;
  20752. }
  20753. setup( builder ) {
  20754. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20755. if ( this.node.isPBO === true ) {
  20756. builder.setupPBO( this.node );
  20757. }
  20758. }
  20759. return super.setup( builder );
  20760. }
  20761. generate( builder, output ) {
  20762. let snippet;
  20763. const isAssignContext = builder.context.assign;
  20764. //
  20765. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  20766. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  20767. snippet = builder.generatePBO( this );
  20768. } else {
  20769. snippet = this.node.build( builder );
  20770. }
  20771. } else {
  20772. snippet = super.generate( builder );
  20773. }
  20774. if ( isAssignContext !== true ) {
  20775. const type = this.getNodeType( builder );
  20776. snippet = builder.format( snippet, type, output );
  20777. }
  20778. return snippet;
  20779. }
  20780. }
  20781. /**
  20782. * TSL function for creating a storage element node.
  20783. *
  20784. * @function
  20785. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  20786. * @param {Node} indexNode - The index node that defines the element access.
  20787. * @returns {StorageArrayElementNode}
  20788. */
  20789. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode );
  20790. /** @module StorageBufferNode **/
  20791. /**
  20792. * This node is used in context of compute shaders and allows to define a
  20793. * storage buffer for data. A typical workflow is to create instances of
  20794. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  20795. * setup up a compute shader that writes into the buffers and then convert
  20796. * the storage buffers to attribute nodes for rendering.
  20797. *
  20798. * ```js
  20799. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  20800. *
  20801. * const computeInit = Fn( () => { // the compute shader
  20802. *
  20803. * const position = positionBuffer.element( instanceIndex );
  20804. *
  20805. * // compute position data
  20806. *
  20807. * position.x = 1;
  20808. * position.y = 1;
  20809. * position.z = 1;
  20810. *
  20811. * } )().compute( particleCount );
  20812. *
  20813. * const particleMaterial = new THREE.SpriteNodeMaterial();
  20814. * particleMaterial.positionNode = positionBuffer.toAttribute();
  20815. *
  20816. * renderer.computeAsync( computeInit );
  20817. *
  20818. * ```
  20819. *
  20820. * @augments BufferNode
  20821. */
  20822. class StorageBufferNode extends BufferNode {
  20823. static get type() {
  20824. return 'StorageBufferNode';
  20825. }
  20826. /**
  20827. * Constructs a new storage buffer node.
  20828. *
  20829. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  20830. * @param {String?} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  20831. * @param {Number} [bufferCount=0] - The buffer count.
  20832. */
  20833. constructor( value, bufferType = null, bufferCount = 0 ) {
  20834. if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  20835. bufferType = getTypeFromLength( value.itemSize );
  20836. bufferCount = value.count;
  20837. }
  20838. super( value, bufferType, bufferCount );
  20839. /**
  20840. * This flag can be used for type testing.
  20841. *
  20842. * @type {Boolean}
  20843. * @readonly
  20844. * @default true
  20845. */
  20846. this.isStorageBufferNode = true;
  20847. /**
  20848. * The access type of the texture node.
  20849. *
  20850. * @type {String}
  20851. * @default 'readWrite'
  20852. */
  20853. this.access = NodeAccess.READ_WRITE;
  20854. /**
  20855. * Whether the node is atomic or not.
  20856. *
  20857. * @type {Boolean}
  20858. * @default false
  20859. */
  20860. this.isAtomic = false;
  20861. /**
  20862. * Whether the node represents a PBO or not.
  20863. * Only relevant for WebGL.
  20864. *
  20865. * @type {Boolean}
  20866. * @default false
  20867. */
  20868. this.isPBO = false;
  20869. /**
  20870. * A reference to the internal buffer attribute node.
  20871. *
  20872. * @type {BufferAttributeNode?}
  20873. * @default null
  20874. */
  20875. this._attribute = null;
  20876. /**
  20877. * A reference to the internal varying node.
  20878. *
  20879. * @type {VaryingNode?}
  20880. * @default null
  20881. */
  20882. this._varying = null;
  20883. /**
  20884. * `StorageBufferNode` sets this property to `true` by default.
  20885. *
  20886. * @type {Boolean}
  20887. * @default true
  20888. */
  20889. this.global = true;
  20890. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  20891. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  20892. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  20893. else value.isStorageBufferAttribute = true;
  20894. }
  20895. }
  20896. /**
  20897. * This method is overwritten since the buffer data might be shared
  20898. * and thus the hash should be shared as well.
  20899. *
  20900. * @param {NodeBuilder} builder - The current node builder.
  20901. * @return {String} The hash.
  20902. */
  20903. getHash( builder ) {
  20904. if ( this.bufferCount === 0 ) {
  20905. let bufferData = builder.globalCache.getData( this.value );
  20906. if ( bufferData === undefined ) {
  20907. bufferData = {
  20908. node: this
  20909. };
  20910. builder.globalCache.setData( this.value, bufferData );
  20911. }
  20912. return bufferData.node.uuid;
  20913. }
  20914. return this.uuid;
  20915. }
  20916. /**
  20917. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  20918. *
  20919. * @param {NodeBuilder} builder - The current node builder.
  20920. * @return {String} The input type.
  20921. */
  20922. getInputType( /*builder*/ ) {
  20923. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  20924. }
  20925. /**
  20926. * Enables element access with the given index node.
  20927. *
  20928. * @param {IndexNode} indexNode - The index node.
  20929. * @return {StorageArrayElementNode} A node representing the element access.
  20930. */
  20931. element( indexNode ) {
  20932. return storageElement( this, indexNode );
  20933. }
  20934. /**
  20935. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  20936. *
  20937. * @param {Boolean} value - The value so set.
  20938. * @return {StorageBufferNode} A reference to this node.
  20939. */
  20940. setPBO( value ) {
  20941. this.isPBO = value;
  20942. return this;
  20943. }
  20944. /**
  20945. * Returns the `isPBO` value.
  20946. *
  20947. * @return {Boolean} Whether the node represents a PBO or not.
  20948. */
  20949. getPBO() {
  20950. return this.isPBO;
  20951. }
  20952. /**
  20953. * Defines the node access.
  20954. *
  20955. * @param {String} value - The node access.
  20956. * @return {StorageBufferNode} A reference to this node.
  20957. */
  20958. setAccess( value ) {
  20959. this.access = value;
  20960. return this;
  20961. }
  20962. /**
  20963. * Convenience method for configuring a read-only node access.
  20964. *
  20965. * @return {StorageBufferNode} A reference to this node.
  20966. */
  20967. toReadOnly() {
  20968. return this.setAccess( NodeAccess.READ_ONLY );
  20969. }
  20970. /**
  20971. * Defines whether the node is atomic or not.
  20972. *
  20973. * @param {Boolean} value - The atomic flag.
  20974. * @return {StorageBufferNode} A reference to this node.
  20975. */
  20976. setAtomic( value ) {
  20977. this.isAtomic = value;
  20978. return this;
  20979. }
  20980. /**
  20981. * Convenience method for making this node atomic.
  20982. *
  20983. * @return {StorageBufferNode} A reference to this node.
  20984. */
  20985. toAtomic() {
  20986. return this.setAtomic( true );
  20987. }
  20988. /**
  20989. * Returns attribute data for this storage buffer node.
  20990. *
  20991. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  20992. */
  20993. getAttributeData() {
  20994. if ( this._attribute === null ) {
  20995. this._attribute = bufferAttribute( this.value );
  20996. this._varying = varying( this._attribute );
  20997. }
  20998. return {
  20999. attribute: this._attribute,
  21000. varying: this._varying
  21001. };
  21002. }
  21003. /**
  21004. * This method is overwritten since the node type from the availability of storage buffers
  21005. * and the attribute data.
  21006. *
  21007. * @param {NodeBuilder} builder - The current node builder.
  21008. * @return {String} The node type.
  21009. */
  21010. getNodeType( builder ) {
  21011. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21012. return super.getNodeType( builder );
  21013. }
  21014. const { attribute } = this.getAttributeData();
  21015. return attribute.getNodeType( builder );
  21016. }
  21017. /**
  21018. * Generates the code snippet of the storage buffer node.
  21019. *
  21020. * @param {NodeBuilder} builder - The current node builder.
  21021. * @return {String} The generated code snippet.
  21022. */
  21023. generate( builder ) {
  21024. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  21025. return super.generate( builder );
  21026. }
  21027. const { attribute, varying } = this.getAttributeData();
  21028. const output = varying.build( builder );
  21029. builder.registerTransform( output, attribute );
  21030. return output;
  21031. }
  21032. }
  21033. /**
  21034. * TSL function for creating a storage buffer node.
  21035. *
  21036. * @function
  21037. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21038. * @param {String?} [type=null] - The buffer type (e.g. `'vec3'`).
  21039. * @param {Number} [count=0] - The buffer count.
  21040. * @returns {StorageBufferNode}
  21041. */
  21042. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  21043. /**
  21044. * @function
  21045. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  21046. *
  21047. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  21048. * @param {String?} type - The buffer type (e.g. `'vec3'`).
  21049. * @param {Number} count - The buffer count.
  21050. * @returns {StorageBufferNode}
  21051. */
  21052. const storageObject = ( value, type, count ) => { // @deprecated, r171
  21053. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  21054. return storage( value, type, count ).setPBO( true );
  21055. };
  21056. /** @module Arrays **/
  21057. /**
  21058. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  21059. *
  21060. * @function
  21061. * @param {Number} count - The data count.
  21062. * @param {String} [type='float'] - The data type.
  21063. * @returns {StorageBufferNode}
  21064. */
  21065. const attributeArray = ( count, type = 'float' ) => {
  21066. const itemSize = getLengthFromType( type );
  21067. const typedArray = getTypedArrayFromType( type );
  21068. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  21069. const node = storage( buffer, type, count );
  21070. return node;
  21071. };
  21072. /**
  21073. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  21074. *
  21075. * @function
  21076. * @param {Number} count - The data count.
  21077. * @param {String} [type='float'] - The data type.
  21078. * @returns {StorageBufferNode}
  21079. */
  21080. const instancedArray = ( count, type = 'float' ) => {
  21081. const itemSize = getLengthFromType( type );
  21082. const typedArray = getTypedArrayFromType( type );
  21083. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  21084. const node = storage( buffer, type, count );
  21085. return node;
  21086. };
  21087. /** @module VertexColorNode **/
  21088. /**
  21089. * An attribute node for representing vertex colors.
  21090. *
  21091. * @augments module:AttributeNode~AttributeNode
  21092. */
  21093. class VertexColorNode extends AttributeNode {
  21094. static get type() {
  21095. return 'VertexColorNode';
  21096. }
  21097. /**
  21098. * Constructs a new vertex color node.
  21099. *
  21100. * @param {Number} [index=0] - The attribute index.
  21101. */
  21102. constructor( index = 0 ) {
  21103. super( null, 'vec4' );
  21104. /**
  21105. * This flag can be used for type testing.
  21106. *
  21107. * @type {Boolean}
  21108. * @readonly
  21109. * @default true
  21110. */
  21111. this.isVertexColorNode = true;
  21112. /**
  21113. * The attribute index to enable more than one sets of vertex colors.
  21114. *
  21115. * @type {Number}
  21116. * @default 0
  21117. */
  21118. this.index = index;
  21119. }
  21120. /**
  21121. * Overwrites the default implementation by honoring the attribute index.
  21122. *
  21123. * @param {NodeBuilder} builder - The current node builder.
  21124. * @return {String} The attribute name.
  21125. */
  21126. getAttributeName( /*builder*/ ) {
  21127. const index = this.index;
  21128. return 'color' + ( index > 0 ? index : '' );
  21129. }
  21130. generate( builder ) {
  21131. const attributeName = this.getAttributeName( builder );
  21132. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  21133. let result;
  21134. if ( geometryAttribute === true ) {
  21135. result = super.generate( builder );
  21136. } else {
  21137. // Vertex color fallback should be white
  21138. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  21139. }
  21140. return result;
  21141. }
  21142. serialize( data ) {
  21143. super.serialize( data );
  21144. data.index = this.index;
  21145. }
  21146. deserialize( data ) {
  21147. super.deserialize( data );
  21148. this.index = data.index;
  21149. }
  21150. }
  21151. /**
  21152. * TSL function for creating a reference node.
  21153. *
  21154. * @function
  21155. * @param {Number} index - The attribute index.
  21156. * @returns {VertexColorNode}
  21157. */
  21158. const vertexColor = ( index ) => nodeObject( new VertexColorNode( index ) );
  21159. /** @module PointUVNode **/
  21160. /**
  21161. * A node for representing the uv coordinates of points.
  21162. *
  21163. * Can only be used with a WebGL backend. In WebGPU, point
  21164. * primitives always have the size of one pixel and can thus
  21165. * can't be used as sprite-like objects that display textures.
  21166. *
  21167. * @augments Node
  21168. */
  21169. class PointUVNode extends Node {
  21170. static get type() {
  21171. return 'PointUVNode';
  21172. }
  21173. /**
  21174. * Constructs a new point uv node.
  21175. */
  21176. constructor() {
  21177. super( 'vec2' );
  21178. /**
  21179. * This flag can be used for type testing.
  21180. *
  21181. * @type {Boolean}
  21182. * @readonly
  21183. * @default true
  21184. */
  21185. this.isPointUVNode = true;
  21186. }
  21187. generate( /*builder*/ ) {
  21188. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  21189. }
  21190. }
  21191. /**
  21192. * TSL object that represents the uv coordinates of points.
  21193. *
  21194. * @type {PointUVNode}
  21195. */
  21196. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  21197. const _e1 = /*@__PURE__*/ new Euler();
  21198. const _m1 = /*@__PURE__*/ new Matrix4();
  21199. /** @module SceneNode **/
  21200. /**
  21201. * This module allows access to a collection of scene properties. The following predefined TSL objects
  21202. * are available for easier use:
  21203. *
  21204. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  21205. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  21206. * - `backgroundRotation`: A node that represents the scene's background rotation.
  21207. *
  21208. * @augments Node
  21209. */
  21210. class SceneNode extends Node {
  21211. static get type() {
  21212. return 'SceneNode';
  21213. }
  21214. /**
  21215. * Constructs a new scene node.
  21216. *
  21217. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  21218. * @param {Scene?} [scene=null] - A reference to the scene.
  21219. */
  21220. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  21221. super();
  21222. /**
  21223. * The scope defines the type of scene property that is accessed.
  21224. *
  21225. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  21226. */
  21227. this.scope = scope;
  21228. /**
  21229. * A reference to the scene that is going to be accessed.
  21230. *
  21231. * @type {Scene?}
  21232. * @default null
  21233. */
  21234. this.scene = scene;
  21235. }
  21236. /**
  21237. * Depending on the scope, the method returns a different type of node that represents
  21238. * the respective scene property.
  21239. *
  21240. * @param {NodeBuilder} builder - The current node builder.
  21241. * @return {Node} The output node.
  21242. */
  21243. setup( builder ) {
  21244. const scope = this.scope;
  21245. const scene = this.scene !== null ? this.scene : builder.scene;
  21246. let output;
  21247. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  21248. output = reference( 'backgroundBlurriness', 'float', scene );
  21249. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  21250. output = reference( 'backgroundIntensity', 'float', scene );
  21251. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  21252. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  21253. const background = scene.background;
  21254. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  21255. _e1.copy( scene.backgroundRotation );
  21256. // accommodate left-handed frame
  21257. _e1.x *= - 1; _e1.y *= - 1; _e1.z *= - 1;
  21258. _m1.makeRotationFromEuler( _e1 );
  21259. } else {
  21260. _m1.identity();
  21261. }
  21262. return _m1;
  21263. } );
  21264. } else {
  21265. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  21266. }
  21267. return output;
  21268. }
  21269. }
  21270. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  21271. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  21272. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  21273. /**
  21274. * TSL object that represents the scene's background blurriness.
  21275. *
  21276. * @type {SceneNode}
  21277. */
  21278. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  21279. /**
  21280. * TSL object that represents the scene's background intensity.
  21281. *
  21282. * @type {SceneNode}
  21283. */
  21284. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  21285. /**
  21286. * TSL object that represents the scene's background rotation.
  21287. *
  21288. * @type {SceneNode}
  21289. */
  21290. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  21291. /** @module StorageTextureNode **/
  21292. /**
  21293. * This special version of a texture node can be used to
  21294. * write data into a storage texture with a compute shader.
  21295. *
  21296. * ```js
  21297. * const storageTexture = new THREE.StorageTexture( width, height );
  21298. *
  21299. * const computeTexture = Fn( ( { storageTexture } ) => {
  21300. *
  21301. * const posX = instanceIndex.modInt( width );
  21302. * const posY = instanceIndex.div( width );
  21303. * const indexUV = uvec2( posX, posY );
  21304. *
  21305. * // generate RGB values
  21306. *
  21307. * const r = 1;
  21308. * const g = 1;
  21309. * const b = 1;
  21310. *
  21311. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  21312. *
  21313. * } );
  21314. *
  21315. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  21316. * renderer.computeAsync( computeNode );
  21317. * ```
  21318. *
  21319. * This node can only be used with a WebGPU backend.
  21320. *
  21321. * @augments module:TextureNode~TextureNode
  21322. */
  21323. class StorageTextureNode extends TextureNode {
  21324. static get type() {
  21325. return 'StorageTextureNode';
  21326. }
  21327. /**
  21328. * Constructs a new storage texture node.
  21329. *
  21330. * @param {StorageTexture} value - The storage texture.
  21331. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21332. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21333. */
  21334. constructor( value, uvNode, storeNode = null ) {
  21335. super( value, uvNode );
  21336. /**
  21337. * The value node that should be stored in the texture.
  21338. *
  21339. * @type {Node?}
  21340. * @default null
  21341. */
  21342. this.storeNode = storeNode;
  21343. /**
  21344. * This flag can be used for type testing.
  21345. *
  21346. * @type {Boolean}
  21347. * @readonly
  21348. * @default true
  21349. */
  21350. this.isStorageTextureNode = true;
  21351. /**
  21352. * The access type of the texture node.
  21353. *
  21354. * @type {String}
  21355. * @default 'writeOnly'
  21356. */
  21357. this.access = NodeAccess.WRITE_ONLY;
  21358. }
  21359. /**
  21360. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  21361. *
  21362. * @param {NodeBuilder} builder - The current node builder.
  21363. * @return {String} The input type.
  21364. */
  21365. getInputType( /*builder*/ ) {
  21366. return 'storageTexture';
  21367. }
  21368. setup( builder ) {
  21369. super.setup( builder );
  21370. const properties = builder.getNodeProperties( this );
  21371. properties.storeNode = this.storeNode;
  21372. }
  21373. /**
  21374. * Defines the node access.
  21375. *
  21376. * @param {String} value - The node access.
  21377. * @return {StorageTextureNode} A reference to this node.
  21378. */
  21379. setAccess( value ) {
  21380. this.access = value;
  21381. return this;
  21382. }
  21383. /**
  21384. * Generates the code snippet of the stroge node. If no `storeNode`
  21385. * is defined, the texture node is generated as normal texture.
  21386. *
  21387. * @param {NodeBuilder} builder - The current node builder.
  21388. * @param {String} output - The current output.
  21389. * @return {String} The generated code snippet.
  21390. */
  21391. generate( builder, output ) {
  21392. let snippet;
  21393. if ( this.storeNode !== null ) {
  21394. snippet = this.generateStore( builder );
  21395. } else {
  21396. snippet = super.generate( builder, output );
  21397. }
  21398. return snippet;
  21399. }
  21400. /**
  21401. * Convenience method for configuring a read/write node access.
  21402. *
  21403. * @return {StorageTextureNode} A reference to this node.
  21404. */
  21405. toReadWrite() {
  21406. return this.setAccess( NodeAccess.READ_WRITE );
  21407. }
  21408. /**
  21409. * Convenience method for configuring a read-only node access.
  21410. *
  21411. * @return {StorageTextureNode} A reference to this node.
  21412. */
  21413. toReadOnly() {
  21414. return this.setAccess( NodeAccess.READ_ONLY );
  21415. }
  21416. /**
  21417. * Convenience method for configuring a write-only node access.
  21418. *
  21419. * @return {StorageTextureNode} A reference to this node.
  21420. */
  21421. toWriteOnly() {
  21422. return this.setAccess( NodeAccess.WRITE_ONLY );
  21423. }
  21424. /**
  21425. * Generates the code snippet of the storage texture node.
  21426. *
  21427. * @param {NodeBuilder} builder - The current node builder.
  21428. */
  21429. generateStore( builder ) {
  21430. const properties = builder.getNodeProperties( this );
  21431. const { uvNode, storeNode } = properties;
  21432. const textureProperty = super.generate( builder, 'property' );
  21433. const uvSnippet = uvNode.build( builder, 'uvec2' );
  21434. const storeSnippet = storeNode.build( builder, 'vec4' );
  21435. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, storeSnippet );
  21436. builder.addLineFlowCode( snippet, this );
  21437. }
  21438. }
  21439. /**
  21440. * TSL function for creating a storage texture node.
  21441. *
  21442. * @function
  21443. * @param {StorageTexture} value - The storage texture.
  21444. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21445. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21446. * @returns {StorageTextureNode}
  21447. */
  21448. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode );
  21449. /**
  21450. * TODO: Explain difference to `storageTexture()`.
  21451. *
  21452. * @function
  21453. * @param {StorageTexture} value - The storage texture.
  21454. * @param {Node<vec2|vec3>} uvNode - The uv node.
  21455. * @param {Node?} [storeNode=null] - The value node that should be stored in the texture.
  21456. * @returns {StorageTextureNode}
  21457. */
  21458. const textureStore = ( value, uvNode, storeNode ) => {
  21459. const node = storageTexture( value, uvNode, storeNode );
  21460. if ( storeNode !== null ) node.append();
  21461. return node;
  21462. };
  21463. /** @module UserDataNode **/
  21464. /**
  21465. * A special type of reference node that allows to link values in
  21466. * `userData` fields to node objects.
  21467. * ```js
  21468. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  21469. *
  21470. * const material = new THREE.SpriteNodeMaterial();
  21471. * material.rotationNode = userData( 'rotation', 'float' );
  21472. * ```
  21473. * Since `UserDataNode` is extended from {@link module:ReferenceNode~ReferenceNode}, the node value
  21474. * will automatically be updated when the `rotation` user data field changes.
  21475. *
  21476. * @augments module:ReferenceNode~ReferenceNode
  21477. */
  21478. class UserDataNode extends ReferenceNode {
  21479. static get type() {
  21480. return 'UserDataNode';
  21481. }
  21482. /**
  21483. * Constructs a new user data node.
  21484. *
  21485. * @param {String} property - The property name that should be referenced by the node.
  21486. * @param {String} inputType - The node data type of the reference.
  21487. * @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.
  21488. */
  21489. constructor( property, inputType, userData = null ) {
  21490. super( property, inputType, userData );
  21491. /**
  21492. * A reference to the `userData` object. If not provided, the `userData`
  21493. * property of the 3D object that uses the node material is evaluated.
  21494. *
  21495. * @type {Object?}
  21496. * @default null
  21497. */
  21498. this.userData = userData;
  21499. }
  21500. /**
  21501. * Overwritten to make sure {@link module:ReferenceNode~ReferenceNode#reference} points to the correct
  21502. * `userData` field.
  21503. *
  21504. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  21505. * @return {Object} A reference to the `userData` field.
  21506. */
  21507. updateReference( state ) {
  21508. this.reference = this.userData !== null ? this.userData : state.object.userData;
  21509. return this.reference;
  21510. }
  21511. }
  21512. /**
  21513. * TSL function for creating a user data node.
  21514. *
  21515. * @function
  21516. * @param {String} name - The property name that should be referenced by the node.
  21517. * @param {String} inputType - The node data type of the reference.
  21518. * @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.
  21519. * @returns {UserDataNode}
  21520. */
  21521. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  21522. const _objectData = new WeakMap();
  21523. /** @module VelocityNode **/
  21524. /**
  21525. * A node for representing motion or velocity vectors. Foundation
  21526. * for advanced post processing effects like motion blur or TRAA.
  21527. *
  21528. * The node keeps track of the model, view and projection matrices
  21529. * of the previous frame and uses them to compute offsets in NDC space.
  21530. * These offsets represent the final velocity.
  21531. *
  21532. * @augments TempNode
  21533. */
  21534. class VelocityNode extends TempNode {
  21535. static get type() {
  21536. return 'VelocityNode';
  21537. }
  21538. /**
  21539. * Constructs a new vertex color node.
  21540. */
  21541. constructor() {
  21542. super( 'vec2' );
  21543. /**
  21544. * The current projection matrix.
  21545. *
  21546. * @type {Matrix4?}
  21547. * @default null
  21548. */
  21549. this.projectionMatrix = null;
  21550. /**
  21551. * Overwritten since velocity nodes are updated per object.
  21552. *
  21553. * @type {String}
  21554. * @default 'object'
  21555. */
  21556. this.updateType = NodeUpdateType.OBJECT;
  21557. /**
  21558. * Overwritten since velocity nodes save data after the update.
  21559. *
  21560. * @type {String}
  21561. * @default 'object'
  21562. */
  21563. this.updateAfterType = NodeUpdateType.OBJECT;
  21564. /**
  21565. * Uniform node representing the previous model matrix in world space.
  21566. *
  21567. * @type {UniformNode<mat4>}
  21568. * @default null
  21569. */
  21570. this.previousModelWorldMatrix = uniform( new Matrix4() );
  21571. /**
  21572. * Uniform node representing the previous projection matrix.
  21573. *
  21574. * @type {UniformNode<mat4>}
  21575. * @default null
  21576. */
  21577. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  21578. /**
  21579. * Uniform node representing the previous view matrix.
  21580. *
  21581. * @type {UniformNode<mat4>}
  21582. * @default null
  21583. */
  21584. this.previousCameraViewMatrix = uniform( new Matrix4() );
  21585. }
  21586. /**
  21587. * Sets the given projection matrix.
  21588. *
  21589. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  21590. */
  21591. setProjectionMatrix( projectionMatrix ) {
  21592. this.projectionMatrix = projectionMatrix;
  21593. }
  21594. /**
  21595. * Updates velocity specific uniforms.
  21596. *
  21597. * @param {NodeFrame} frame - A reference to the current node frame.
  21598. */
  21599. update( { frameId, camera, object } ) {
  21600. const previousModelMatrix = getPreviousMatrix( object );
  21601. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  21602. //
  21603. const cameraData = getData( camera );
  21604. if ( cameraData.frameId !== frameId ) {
  21605. cameraData.frameId = frameId;
  21606. if ( cameraData.previousProjectionMatrix === undefined ) {
  21607. cameraData.previousProjectionMatrix = new Matrix4();
  21608. cameraData.previousCameraViewMatrix = new Matrix4();
  21609. cameraData.currentProjectionMatrix = new Matrix4();
  21610. cameraData.currentCameraViewMatrix = new Matrix4();
  21611. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21612. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  21613. } else {
  21614. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  21615. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  21616. }
  21617. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  21618. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  21619. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  21620. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  21621. }
  21622. }
  21623. /**
  21624. * Overwritten to updated velocity specific uniforms.
  21625. *
  21626. * @param {NodeFrame} frame - A reference to the current node frame.
  21627. */
  21628. updateAfter( { object } ) {
  21629. getPreviousMatrix( object ).copy( object.matrixWorld );
  21630. }
  21631. /**
  21632. * Implements the velocity computation based on the previous and current vertex data.
  21633. *
  21634. * @param {NodeBuilder} builder - A reference to the current node builder.
  21635. * @return {Node<vec2>} The motion vector.
  21636. */
  21637. setup( /*builder*/ ) {
  21638. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  21639. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  21640. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  21641. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  21642. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  21643. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  21644. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  21645. return velocity;
  21646. }
  21647. }
  21648. function getData( object ) {
  21649. let objectData = _objectData.get( object );
  21650. if ( objectData === undefined ) {
  21651. objectData = {};
  21652. _objectData.set( object, objectData );
  21653. }
  21654. return objectData;
  21655. }
  21656. function getPreviousMatrix( object, index = 0 ) {
  21657. const objectData = getData( object );
  21658. let matrix = objectData[ index ];
  21659. if ( matrix === undefined ) {
  21660. objectData[ index ] = matrix = new Matrix4();
  21661. }
  21662. return matrix;
  21663. }
  21664. /**
  21665. * TSL object that represents the velocity of a render pass.
  21666. *
  21667. * @type {VelocityNode}
  21668. */
  21669. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  21670. /** @module BlendModes **/
  21671. /**
  21672. * Represents a "Color Burn" blend mode.
  21673. *
  21674. * It's designed to darken the base layer's colors based on the color of the blend layer.
  21675. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  21676. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  21677. *
  21678. * @method
  21679. * @param {Node<vec3>} base - The base color.
  21680. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  21681. * @return {Node<vec3>} The result.
  21682. */
  21683. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21684. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  21685. } ).setLayout( {
  21686. name: 'blendBurn',
  21687. type: 'vec3',
  21688. inputs: [
  21689. { name: 'base', type: 'vec3' },
  21690. { name: 'blend', type: 'vec3' }
  21691. ]
  21692. } );
  21693. /**
  21694. * Represents a "Color Dodge" blend mode.
  21695. *
  21696. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  21697. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  21698. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  21699. *
  21700. * @method
  21701. * @param {Node<vec3>} base - The base color.
  21702. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21703. * @return {Node<vec3>} The result.
  21704. */
  21705. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21706. return min$1( base.div( blend.oneMinus() ), 1.0 );
  21707. } ).setLayout( {
  21708. name: 'blendDodge',
  21709. type: 'vec3',
  21710. inputs: [
  21711. { name: 'base', type: 'vec3' },
  21712. { name: 'blend', type: 'vec3' }
  21713. ]
  21714. } );
  21715. /**
  21716. * Represents a "Screen" blend mode.
  21717. *
  21718. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  21719. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  21720. * effects.
  21721. *
  21722. * @method
  21723. * @param {Node<vec3>} base - The base color.
  21724. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  21725. * @return {Node<vec3>} The result.
  21726. */
  21727. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21728. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  21729. } ).setLayout( {
  21730. name: 'blendScreen',
  21731. type: 'vec3',
  21732. inputs: [
  21733. { name: 'base', type: 'vec3' },
  21734. { name: 'blend', type: 'vec3' }
  21735. ]
  21736. } );
  21737. /**
  21738. * Represents a "Overlay" blend mode.
  21739. *
  21740. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  21741. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  21742. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  21743. *
  21744. * @method
  21745. * @param {Node<vec3>} base - The base color.
  21746. * @param {Node<vec3>} blend - The blend color
  21747. * @return {Node<vec3>} The result.
  21748. */
  21749. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21750. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  21751. } ).setLayout( {
  21752. name: 'blendOverlay',
  21753. type: 'vec3',
  21754. inputs: [
  21755. { name: 'base', type: 'vec3' },
  21756. { name: 'blend', type: 'vec3' }
  21757. ]
  21758. } );
  21759. /**
  21760. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  21761. * It assumes both input colors have non-preumiltiplied alpha.
  21762. *
  21763. * @method
  21764. * @param {Node<vec4>} base - The base color.
  21765. * @param {Node<vec4>} blend - The blend color
  21766. * @return {Node<vec4>} The result.
  21767. */
  21768. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  21769. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  21770. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  21771. } ).setLayout( {
  21772. name: 'blendColor',
  21773. type: 'vec4',
  21774. inputs: [
  21775. { name: 'base', type: 'vec4' },
  21776. { name: 'blend', type: 'vec4' }
  21777. ]
  21778. } );
  21779. // deprecated
  21780. /**
  21781. * @function
  21782. * @deprecated since r171. Use {@link blendBurn} instead.
  21783. *
  21784. * @param {...any} params
  21785. * @returns {Function}
  21786. */
  21787. const burn = ( ...params ) => { // @deprecated, r171
  21788. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  21789. return blendBurn( params );
  21790. };
  21791. /**
  21792. * @function
  21793. * @deprecated since r171. Use {@link blendDodge} instead.
  21794. *
  21795. * @param {...any} params
  21796. * @returns {Function}
  21797. */
  21798. const dodge = ( ...params ) => { // @deprecated, r171
  21799. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  21800. return blendDodge( params );
  21801. };
  21802. /**
  21803. * @method
  21804. * @deprecated since r171. Use {@link blendScreen} instead.
  21805. *
  21806. * @param {...any} params
  21807. * @returns {Function}
  21808. */
  21809. const screen = ( ...params ) => { // @deprecated, r171
  21810. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  21811. return blendScreen( params );
  21812. };
  21813. /**
  21814. * @method
  21815. * @deprecated since r171. Use {@link blendOverlay} instead.
  21816. *
  21817. * @param {...any} params
  21818. * @returns {Function}
  21819. */
  21820. const overlay = ( ...params ) => { // @deprecated, r171
  21821. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  21822. return blendOverlay( params );
  21823. };
  21824. /** @module ColorAdjustment **/
  21825. /**
  21826. * Computes a grayscale value for the given RGB color value.
  21827. *
  21828. * @method
  21829. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  21830. * @return {Node<vec3>} The grayscale color.
  21831. */
  21832. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  21833. return luminance( color.rgb );
  21834. } );
  21835. /**
  21836. * Super-saturates or desaturates the given RGB color.
  21837. *
  21838. * @method
  21839. * @param {Node<vec3>} color - The input color.
  21840. * @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.
  21841. * @return {Node<vec3>} The saturated color.
  21842. */
  21843. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21844. return adjustment.mix( luminance( color.rgb ), color.rgb );
  21845. } );
  21846. /**
  21847. * Selectively enhance the intensity of less saturated RGB colors. Can result
  21848. * in a more natural and visually appealing image with enhanced color depth
  21849. * compared to {@link ColorAdjustment#saturation}.
  21850. *
  21851. * @method
  21852. * @param {Node<vec3>} color - The input color.
  21853. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  21854. * @return {Node<vec3>} The updated color.
  21855. */
  21856. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21857. const average = add( color.r, color.g, color.b ).div( 3.0 );
  21858. const mx = color.r.max( color.g.max( color.b ) );
  21859. const amt = mx.sub( average ).mul( adjustment ).mul( - 3.0 );
  21860. return mix( color.rgb, mx, amt );
  21861. } );
  21862. /**
  21863. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  21864. *
  21865. * @method
  21866. * @param {Node<vec3>} color - The input color.
  21867. * @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.
  21868. * @return {Node<vec3>} The updated color.
  21869. */
  21870. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  21871. const k = vec3( 0.57735, 0.57735, 0.57735 );
  21872. const cosAngle = adjustment.cos();
  21873. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  21874. } );
  21875. /**
  21876. * Computes the luminance for the given RGB color value.
  21877. *
  21878. * @method
  21879. * @param {Node<vec3>} color - The color value to compute the luminance for.
  21880. * @param {Node<vec3>?} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  21881. * @return {Node<vec3>} The luminance.
  21882. */
  21883. const luminance = (
  21884. color,
  21885. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  21886. ) => dot( color, luminanceCoefficients );
  21887. /**
  21888. * Color Decision List (CDL) v1.2
  21889. *
  21890. * Compact representation of color grading information, defined by slope, offset, power, and
  21891. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  21892. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  21893. *
  21894. * @method
  21895. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  21896. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  21897. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  21898. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  21899. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  21900. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  21901. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  21902. *
  21903. * References:
  21904. * - ASC CDL v1.2
  21905. * - {@link https://blender.stackexchange.com/a/55239/43930}
  21906. * - {@link https://docs.acescentral.com/specifications/acescc/}
  21907. */
  21908. const cdl = /*@__PURE__*/ Fn( ( [
  21909. color,
  21910. slope = vec3( 1 ),
  21911. offset = vec3( 0 ),
  21912. power = vec3( 1 ),
  21913. saturation = float( 1 ),
  21914. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  21915. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  21916. ] ) => {
  21917. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  21918. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  21919. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  21920. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  21921. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  21922. const pv = v.pow( power ).toVar();
  21923. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  21924. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  21925. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  21926. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  21927. return vec4( v.rgb, color.a );
  21928. } );
  21929. /** @module PosterizeNode **/
  21930. /**
  21931. * Represents a posterize effect which reduces the number of colors
  21932. * in an image, resulting in a more blocky and stylized appearance.
  21933. *
  21934. * @augments TempNode
  21935. */
  21936. class PosterizeNode extends TempNode {
  21937. static get type() {
  21938. return 'PosterizeNode';
  21939. }
  21940. /**
  21941. * Constructs a new posterize node.
  21942. *
  21943. * @param {Node} sourceNode - The input color.
  21944. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21945. */
  21946. constructor( sourceNode, stepsNode ) {
  21947. super();
  21948. /**
  21949. * The input color.
  21950. *
  21951. * @type {Node}
  21952. */
  21953. this.sourceNode = sourceNode;
  21954. /**
  21955. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21956. *
  21957. * @type {Node}
  21958. */
  21959. this.stepsNode = stepsNode;
  21960. }
  21961. setup() {
  21962. const { sourceNode, stepsNode } = this;
  21963. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  21964. }
  21965. }
  21966. /**
  21967. * TSL function for creating a posterize node.
  21968. *
  21969. * @function
  21970. * @param {Node} sourceNode - The input color.
  21971. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  21972. * @returns {PosterizeNode}
  21973. */
  21974. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode );
  21975. /** @module PassNode **/
  21976. const _size = /*@__PURE__*/ new Vector2();
  21977. /**
  21978. * Represents the texture of a pass node.
  21979. *
  21980. * @augments module:TextureNode~TextureNode
  21981. */
  21982. class PassTextureNode extends TextureNode {
  21983. static get type() {
  21984. return 'PassTextureNode';
  21985. }
  21986. /**
  21987. * Constructs a new pass texture node.
  21988. *
  21989. * @param {PassNode} passNode - The pass node.
  21990. * @param {Texture} texture - The output texture.
  21991. */
  21992. constructor( passNode, texture ) {
  21993. super( texture );
  21994. /**
  21995. * A reference to the pass node.
  21996. *
  21997. * @type {PassNode}
  21998. */
  21999. this.passNode = passNode;
  22000. this.setUpdateMatrix( false );
  22001. }
  22002. setup( builder ) {
  22003. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  22004. return super.setup( builder );
  22005. }
  22006. clone() {
  22007. return new this.constructor( this.passNode, this.value );
  22008. }
  22009. }
  22010. /**
  22011. * An extension of `PassTextureNode` which allows to manage more than one
  22012. * internal texture. Relevant for the `getPreviousTexture()` related API.
  22013. *
  22014. * @augments module:PassTextureNode~PassTextureNode
  22015. */
  22016. class PassMultipleTextureNode extends PassTextureNode {
  22017. static get type() {
  22018. return 'PassMultipleTextureNode';
  22019. }
  22020. /**
  22021. * Constructs a new pass texture node.
  22022. *
  22023. * @param {PassNode} passNode - The pass node.
  22024. * @param {String} textureName - The output texture name.
  22025. * @param {Boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  22026. */
  22027. constructor( passNode, textureName, previousTexture = false ) {
  22028. // null is passed to the super call since this class does not
  22029. // use an external texture for rendering pass data into. Instead
  22030. // the texture is managed by the pass node itself
  22031. super( passNode, null );
  22032. /**
  22033. * The output texture name.
  22034. *
  22035. * @type {String}
  22036. */
  22037. this.textureName = textureName;
  22038. /**
  22039. * Whether previous frame data should be used or not.
  22040. *
  22041. * @type {Boolean}
  22042. */
  22043. this.previousTexture = previousTexture;
  22044. }
  22045. /**
  22046. * Updates the texture reference of this node.
  22047. */
  22048. updateTexture() {
  22049. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  22050. }
  22051. setup( builder ) {
  22052. this.updateTexture();
  22053. return super.setup( builder );
  22054. }
  22055. clone() {
  22056. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  22057. }
  22058. }
  22059. /**
  22060. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  22061. * This pass produces a render for the given scene and camera and can provide multiple outputs
  22062. * via MRT for further processing.
  22063. *
  22064. * ```js
  22065. * const postProcessing = new PostProcessing( renderer );
  22066. *
  22067. * const scenePass = pass( scene, camera );
  22068. *
  22069. * postProcessing.outputNode = scenePass;
  22070. * ```
  22071. *
  22072. * @augments TempNode
  22073. */
  22074. class PassNode extends TempNode {
  22075. static get type() {
  22076. return 'PassNode';
  22077. }
  22078. /**
  22079. * Constructs a new pass node.
  22080. *
  22081. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  22082. * @param {Scene} scene - A reference to the scene.
  22083. * @param {Camera} camera - A reference to the camera.
  22084. * @param {Object} options - Options for the internal render target.
  22085. */
  22086. constructor( scope, scene, camera, options = {} ) {
  22087. super( 'vec4' );
  22088. /**
  22089. * The scope of the pass. The scope determines whether the node outputs color or depth.
  22090. *
  22091. * @type {('color'|'depth')}
  22092. */
  22093. this.scope = scope;
  22094. /**
  22095. * A reference to the scene.
  22096. *
  22097. * @type {Scene}
  22098. */
  22099. this.scene = scene;
  22100. /**
  22101. * A reference to the camera.
  22102. *
  22103. * @type {Camera}
  22104. */
  22105. this.camera = camera;
  22106. /**
  22107. * Options for the internal render target.
  22108. *
  22109. * @type {Object}
  22110. */
  22111. this.options = options;
  22112. /**
  22113. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  22114. *
  22115. * @private
  22116. * @type {Number}
  22117. * @default 1
  22118. */
  22119. this._pixelRatio = 1;
  22120. /**
  22121. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  22122. * @private
  22123. * @type {Number}
  22124. * @default 1
  22125. */
  22126. this._width = 1;
  22127. /**
  22128. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  22129. * @private
  22130. * @type {Number}
  22131. * @default 1
  22132. */
  22133. this._height = 1;
  22134. const depthTexture = new DepthTexture();
  22135. depthTexture.isRenderTargetTexture = true;
  22136. //depthTexture.type = FloatType;
  22137. depthTexture.name = 'depth';
  22138. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  22139. renderTarget.texture.name = 'output';
  22140. renderTarget.depthTexture = depthTexture;
  22141. /**
  22142. * The pass's render target.
  22143. *
  22144. * @type {RenderTarget}
  22145. */
  22146. this.renderTarget = renderTarget;
  22147. /**
  22148. * A dictionary holding the internal result textures.
  22149. *
  22150. * @private
  22151. * @type {Object<String, Texture>}
  22152. */
  22153. this._textures = {
  22154. output: renderTarget.texture,
  22155. depth: depthTexture
  22156. };
  22157. /**
  22158. * A dictionary holding the internal texture nodes.
  22159. *
  22160. * @private
  22161. * @type {Object<String, TextureNode>}
  22162. */
  22163. this._textureNodes = {};
  22164. /**
  22165. * A dictionary holding the internal depth nodes.
  22166. *
  22167. * @private
  22168. * @type {Object}
  22169. */
  22170. this._linearDepthNodes = {};
  22171. /**
  22172. * A dictionary holding the internal viewZ nodes.
  22173. *
  22174. * @private
  22175. * @type {Object}
  22176. */
  22177. this._viewZNodes = {};
  22178. /**
  22179. * A dictionary holding the texture data of the previous frame.
  22180. * Used for computing velocity/motion vectors.
  22181. *
  22182. * @private
  22183. * @type {Object<String, Texture>}
  22184. */
  22185. this._previousTextures = {};
  22186. /**
  22187. * A dictionary holding the texture nodes of the previous frame.
  22188. * Used for computing velocity/motion vectors.
  22189. *
  22190. * @private
  22191. * @type {Object<String, TextureNode>}
  22192. */
  22193. this._previousTextureNodes = {};
  22194. /**
  22195. * The `near` property of the camera as a uniform.
  22196. *
  22197. * @private
  22198. * @type {UniformNode}
  22199. */
  22200. this._cameraNear = uniform( 0 );
  22201. /**
  22202. * The `far` property of the camera as a uniform.
  22203. *
  22204. * @private
  22205. * @type {UniformNode}
  22206. */
  22207. this._cameraFar = uniform( 0 );
  22208. /**
  22209. * A MRT node configuring the MRT settings.
  22210. *
  22211. * @private
  22212. * @type {MRTNode?}
  22213. * @default null
  22214. */
  22215. this._mrt = null;
  22216. /**
  22217. * This flag can be used for type testing.
  22218. *
  22219. * @type {Boolean}
  22220. * @readonly
  22221. * @default true
  22222. */
  22223. this.isPassNode = true;
  22224. /**
  22225. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  22226. * scene once per frame in its {@link PassNode#updateBefore} method.
  22227. *
  22228. * @type {String}
  22229. * @default 'frame'
  22230. */
  22231. this.updateBeforeType = NodeUpdateType.FRAME;
  22232. }
  22233. /**
  22234. * Sets the given MRT node to setup MRT for this pass.
  22235. *
  22236. * @param {MRTNode} mrt - The MRT object.
  22237. * @return {PassNode} A reference to this pass.
  22238. */
  22239. setMRT( mrt ) {
  22240. this._mrt = mrt;
  22241. return this;
  22242. }
  22243. /**
  22244. * Returns the current MRT node.
  22245. *
  22246. * @return {MRTNode} The current MRT node.
  22247. */
  22248. getMRT() {
  22249. return this._mrt;
  22250. }
  22251. /**
  22252. * The method is overwritten so it always returns `true`.
  22253. *
  22254. * @return {Boolean} Whether this node is global or not.
  22255. */
  22256. isGlobal() {
  22257. return true;
  22258. }
  22259. /**
  22260. * Returns the texture for the given output name.
  22261. *
  22262. * @param {String} name - The output name to get the texture for.
  22263. * @return {Texture} The texture.
  22264. */
  22265. getTexture( name ) {
  22266. let texture = this._textures[ name ];
  22267. if ( texture === undefined ) {
  22268. const refTexture = this.renderTarget.texture;
  22269. texture = refTexture.clone();
  22270. texture.name = name;
  22271. this._textures[ name ] = texture;
  22272. this.renderTarget.textures.push( texture );
  22273. }
  22274. return texture;
  22275. }
  22276. /**
  22277. * Returns the texture holding the data of the previous frame for the given output name.
  22278. *
  22279. * @param {String} name - The output name to get the texture for.
  22280. * @return {Texture} The texture holding the data of the previous frame.
  22281. */
  22282. getPreviousTexture( name ) {
  22283. let texture = this._previousTextures[ name ];
  22284. if ( texture === undefined ) {
  22285. texture = this.getTexture( name ).clone();
  22286. this._previousTextures[ name ] = texture;
  22287. }
  22288. return texture;
  22289. }
  22290. /**
  22291. * Switches current and previous textures for the given output name.
  22292. *
  22293. * @param {String} name - The output name.
  22294. */
  22295. toggleTexture( name ) {
  22296. const prevTexture = this._previousTextures[ name ];
  22297. if ( prevTexture !== undefined ) {
  22298. const texture = this._textures[ name ];
  22299. const index = this.renderTarget.textures.indexOf( texture );
  22300. this.renderTarget.textures[ index ] = prevTexture;
  22301. this._textures[ name ] = prevTexture;
  22302. this._previousTextures[ name ] = texture;
  22303. this._textureNodes[ name ].updateTexture();
  22304. this._previousTextureNodes[ name ].updateTexture();
  22305. }
  22306. }
  22307. /**
  22308. * Returns the texture node for the given output name.
  22309. *
  22310. * @param {String} [name='output'] - The output name to get the texture node for.
  22311. * @return {TextureNode} The texture node.
  22312. */
  22313. getTextureNode( name = 'output' ) {
  22314. let textureNode = this._textureNodes[ name ];
  22315. if ( textureNode === undefined ) {
  22316. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  22317. textureNode.updateTexture();
  22318. this._textureNodes[ name ] = textureNode;
  22319. }
  22320. return textureNode;
  22321. }
  22322. /**
  22323. * Returns the previous texture node for the given output name.
  22324. *
  22325. * @param {String} [name='output'] - The output name to get the previous texture node for.
  22326. * @return {TextureNode} The previous texture node.
  22327. */
  22328. getPreviousTextureNode( name = 'output' ) {
  22329. let textureNode = this._previousTextureNodes[ name ];
  22330. if ( textureNode === undefined ) {
  22331. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  22332. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  22333. textureNode.updateTexture();
  22334. this._previousTextureNodes[ name ] = textureNode;
  22335. }
  22336. return textureNode;
  22337. }
  22338. /**
  22339. * Returns a viewZ node of this pass.
  22340. *
  22341. * @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.
  22342. * @return {Node} The viewZ node.
  22343. */
  22344. getViewZNode( name = 'depth' ) {
  22345. let viewZNode = this._viewZNodes[ name ];
  22346. if ( viewZNode === undefined ) {
  22347. const cameraNear = this._cameraNear;
  22348. const cameraFar = this._cameraFar;
  22349. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  22350. }
  22351. return viewZNode;
  22352. }
  22353. /**
  22354. * Returns a linear depth node of this pass.
  22355. *
  22356. * @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.
  22357. * @return {Node} The linear depth node.
  22358. */
  22359. getLinearDepthNode( name = 'depth' ) {
  22360. let linearDepthNode = this._linearDepthNodes[ name ];
  22361. if ( linearDepthNode === undefined ) {
  22362. const cameraNear = this._cameraNear;
  22363. const cameraFar = this._cameraFar;
  22364. const viewZNode = this.getViewZNode( name );
  22365. // TODO: just if ( builder.camera.isPerspectiveCamera )
  22366. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  22367. }
  22368. return linearDepthNode;
  22369. }
  22370. setup( { renderer } ) {
  22371. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  22372. // Disable MSAA for WebGL backend for now
  22373. if ( renderer.backend.isWebGLBackend === true ) {
  22374. this.renderTarget.samples = 0;
  22375. }
  22376. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  22377. }
  22378. updateBefore( frame ) {
  22379. const { renderer } = frame;
  22380. const { scene, camera } = this;
  22381. this._pixelRatio = renderer.getPixelRatio();
  22382. const size = renderer.getSize( _size );
  22383. this.setSize( size.width, size.height );
  22384. const currentRenderTarget = renderer.getRenderTarget();
  22385. const currentMRT = renderer.getMRT();
  22386. this._cameraNear.value = camera.near;
  22387. this._cameraFar.value = camera.far;
  22388. for ( const name in this._previousTextures ) {
  22389. this.toggleTexture( name );
  22390. }
  22391. renderer.setRenderTarget( this.renderTarget );
  22392. renderer.setMRT( this._mrt );
  22393. renderer.render( scene, camera );
  22394. renderer.setRenderTarget( currentRenderTarget );
  22395. renderer.setMRT( currentMRT );
  22396. }
  22397. /**
  22398. * Sets the size of the pass's render target. Honors the pixel ratio.
  22399. *
  22400. * @param {Number} width - The width to set.
  22401. * @param {Number} height - The height to set.
  22402. */
  22403. setSize( width, height ) {
  22404. this._width = width;
  22405. this._height = height;
  22406. const effectiveWidth = this._width * this._pixelRatio;
  22407. const effectiveHeight = this._height * this._pixelRatio;
  22408. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  22409. }
  22410. /**
  22411. * Sets the pixel ratio the pass's render target and updates the size.
  22412. *
  22413. * @param {Number} pixelRatio - The pixel ratio to set.
  22414. */
  22415. setPixelRatio( pixelRatio ) {
  22416. this._pixelRatio = pixelRatio;
  22417. this.setSize( this._width, this._height );
  22418. }
  22419. /**
  22420. * Frees internal resources. Should be called when the node is no longer in use.
  22421. */
  22422. dispose() {
  22423. this.renderTarget.dispose();
  22424. }
  22425. }
  22426. PassNode.COLOR = 'color';
  22427. PassNode.DEPTH = 'depth';
  22428. /**
  22429. * TSL function for creating a pass node.
  22430. *
  22431. * @function
  22432. * @param {Scene} scene - A reference to the scene.
  22433. * @param {Camera} camera - A reference to the camera.
  22434. * @param {Object} options - Options for the internal render target.
  22435. * @returns {PassNode}
  22436. */
  22437. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  22438. /**
  22439. * TSL function for creating a pass texture node.
  22440. *
  22441. * @function
  22442. * @param {PassNode} pass - The pass node.
  22443. * @param {Texture} texture - The output texture.
  22444. * @returns {PassTextureNode}
  22445. */
  22446. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  22447. /**
  22448. * TSL function for creating a depth pass node.
  22449. *
  22450. * @function
  22451. * @param {Scene} scene - A reference to the scene.
  22452. * @param {Camera} camera - A reference to the camera.
  22453. * @param {Object} options - Options for the internal render target.
  22454. * @returns {PassNode}
  22455. */
  22456. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  22457. /** @module ToonOutlinePassNode **/
  22458. /**
  22459. * Represents a render pass for producing a toon outline effect on compatible objects.
  22460. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  22461. * will receive the outline.
  22462. *
  22463. * ```js
  22464. * const postProcessing = new PostProcessing( renderer );
  22465. *
  22466. * const scenePass = toonOutlinePass( scene, camera );
  22467. *
  22468. * postProcessing.outputNode = scenePass;
  22469. * ```
  22470. * @augments PassNode
  22471. */
  22472. class ToonOutlinePassNode extends PassNode {
  22473. static get type() {
  22474. return 'ToonOutlinePassNode';
  22475. }
  22476. /**
  22477. * Constructs a new outline pass node.
  22478. *
  22479. * @param {Scene} scene - A reference to the scene.
  22480. * @param {Camera} camera - A reference to the camera.
  22481. * @param {Node} colorNode - Defines the outline's color.
  22482. * @param {Node} thicknessNode - Defines the outline's thickness.
  22483. * @param {Node} alphaNode - Defines the outline's alpha.
  22484. */
  22485. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  22486. super( PassNode.COLOR, scene, camera );
  22487. /**
  22488. * Defines the outline's color.
  22489. *
  22490. * @type {Node}
  22491. */
  22492. this.colorNode = colorNode;
  22493. /**
  22494. * Defines the outline's thickness.
  22495. *
  22496. * @type {Node}
  22497. */
  22498. this.thicknessNode = thicknessNode;
  22499. /**
  22500. * Defines the outline's alpha.
  22501. *
  22502. * @type {Node}
  22503. */
  22504. this.alphaNode = alphaNode;
  22505. /**
  22506. * An internal material cache.
  22507. *
  22508. * @private
  22509. * @type {WeakMap<Material, NodeMaterial>}
  22510. */
  22511. this._materialCache = new WeakMap();
  22512. }
  22513. updateBefore( frame ) {
  22514. const { renderer } = frame;
  22515. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  22516. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  22517. // only render outline for supported materials
  22518. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  22519. if ( material.wireframe === false ) {
  22520. const outlineMaterial = this._getOutlineMaterial( material );
  22521. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  22522. }
  22523. }
  22524. // default
  22525. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  22526. } );
  22527. super.updateBefore( frame );
  22528. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  22529. }
  22530. /**
  22531. * Creates the material used for outline rendering.
  22532. *
  22533. * @private
  22534. * @return {NodeMaterial} The outline material.
  22535. */
  22536. _createMaterial() {
  22537. const material = new NodeMaterial();
  22538. material.isMeshToonOutlineMaterial = true;
  22539. material.name = 'Toon_Outline';
  22540. material.side = BackSide;
  22541. // vertex node
  22542. const outlineNormal = normalLocal.negate();
  22543. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  22544. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  22545. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  22546. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  22547. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  22548. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  22549. // color node
  22550. material.colorNode = vec4( this.colorNode, this.alphaNode );
  22551. return material;
  22552. }
  22553. /**
  22554. * For the given toon material, this method returns a corresponding
  22555. * outline material.
  22556. *
  22557. * @private
  22558. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  22559. * @return {NodeMaterial} The outline material.
  22560. */
  22561. _getOutlineMaterial( originalMaterial ) {
  22562. let outlineMaterial = this._materialCache.get( originalMaterial );
  22563. if ( outlineMaterial === undefined ) {
  22564. outlineMaterial = this._createMaterial();
  22565. this._materialCache.set( originalMaterial, outlineMaterial );
  22566. }
  22567. return outlineMaterial;
  22568. }
  22569. }
  22570. /**
  22571. * TSL function for creating a toon outline pass node.
  22572. *
  22573. * @function
  22574. * @param {Scene} scene - A reference to the scene.
  22575. * @param {Camera} camera - A reference to the camera.
  22576. * @param {Color} color - Defines the outline's color.
  22577. * @param {Number} [thickness=0.003] - Defines the outline's thickness.
  22578. * @param {Number} [alpha=1] - Defines the outline's alpha.
  22579. * @returns {ToonOutlinePassNode}
  22580. */
  22581. 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 ) ) );
  22582. /** @module ToneMappingFunctions **/
  22583. /**
  22584. * Linear tone mapping, exposure only.
  22585. *
  22586. * @method
  22587. * @param {Node<vec3>} color - The color that should be tone mapped.
  22588. * @param {Node<float>} exposure - The exposure.
  22589. * @return {Node<vec3>} The tone mapped color.
  22590. */
  22591. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22592. return color.mul( exposure ).clamp();
  22593. } ).setLayout( {
  22594. name: 'linearToneMapping',
  22595. type: 'vec3',
  22596. inputs: [
  22597. { name: 'color', type: 'vec3' },
  22598. { name: 'exposure', type: 'float' }
  22599. ]
  22600. } );
  22601. /**
  22602. * Reinhard tone mapping.
  22603. *
  22604. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  22605. *
  22606. * @method
  22607. * @param {Node<vec3>} color - The color that should be tone mapped.
  22608. * @param {Node<float>} exposure - The exposure.
  22609. * @return {Node<vec3>} The tone mapped color.
  22610. */
  22611. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22612. color = color.mul( exposure );
  22613. return color.div( color.add( 1.0 ) ).clamp();
  22614. } ).setLayout( {
  22615. name: 'reinhardToneMapping',
  22616. type: 'vec3',
  22617. inputs: [
  22618. { name: 'color', type: 'vec3' },
  22619. { name: 'exposure', type: 'float' }
  22620. ]
  22621. } );
  22622. /**
  22623. * Cineon tone mapping.
  22624. *
  22625. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  22626. *
  22627. * @method
  22628. * @param {Node<vec3>} color - The color that should be tone mapped.
  22629. * @param {Node<float>} exposure - The exposure.
  22630. * @return {Node<vec3>} The tone mapped color.
  22631. */
  22632. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22633. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  22634. color = color.mul( exposure );
  22635. color = color.sub( 0.004 ).max( 0.0 );
  22636. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  22637. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  22638. return a.div( b ).pow( 2.2 );
  22639. } ).setLayout( {
  22640. name: 'cineonToneMapping',
  22641. type: 'vec3',
  22642. inputs: [
  22643. { name: 'color', type: 'vec3' },
  22644. { name: 'exposure', type: 'float' }
  22645. ]
  22646. } );
  22647. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  22648. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  22649. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  22650. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  22651. return a.div( b );
  22652. } );
  22653. /**
  22654. * ACESFilmic tone mapping.
  22655. *
  22656. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  22657. *
  22658. * @method
  22659. * @param {Node<vec3>} color - The color that should be tone mapped.
  22660. * @param {Node<float>} exposure - The exposure.
  22661. * @return {Node<vec3>} The tone mapped color.
  22662. */
  22663. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22664. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  22665. const ACESInputMat = mat3(
  22666. 0.59719, 0.35458, 0.04823,
  22667. 0.07600, 0.90834, 0.01566,
  22668. 0.02840, 0.13383, 0.83777
  22669. );
  22670. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  22671. const ACESOutputMat = mat3(
  22672. 1.60475, - 0.53108, - 0.07367,
  22673. - 0.10208, 1.10813, - 0.00605,
  22674. - 0.00327, - 0.07276, 1.07602
  22675. );
  22676. color = color.mul( exposure ).div( 0.6 );
  22677. color = ACESInputMat.mul( color );
  22678. // Apply RRT and ODT
  22679. color = RRTAndODTFit( color );
  22680. color = ACESOutputMat.mul( color );
  22681. // Clamp to [0, 1]
  22682. return color.clamp();
  22683. } ).setLayout( {
  22684. name: 'acesFilmicToneMapping',
  22685. type: 'vec3',
  22686. inputs: [
  22687. { name: 'color', type: 'vec3' },
  22688. { name: 'exposure', type: 'float' }
  22689. ]
  22690. } );
  22691. const LINEAR_REC2020_TO_LINEAR_SRGB = /*@__PURE__*/ mat3( vec3( 1.6605, - 0.1246, - 0.0182 ), vec3( - 0.5876, 1.1329, - 0.1006 ), vec3( - 0.0728, - 0.0083, 1.1187 ) );
  22692. 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 ) );
  22693. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  22694. const x = vec3( x_immutable ).toVar();
  22695. const x2 = vec3( x.mul( x ) ).toVar();
  22696. const x4 = vec3( x2.mul( x2 ) ).toVar();
  22697. 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 ) ) ) );
  22698. } );
  22699. /**
  22700. * AgX tone mapping.
  22701. *
  22702. * @method
  22703. * @param {Node<vec3>} color - The color that should be tone mapped.
  22704. * @param {Node<float>} exposure - The exposure.
  22705. * @return {Node<vec3>} The tone mapped color.
  22706. */
  22707. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22708. const colortone = vec3( color ).toVar();
  22709. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  22710. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) );
  22711. const AgxMinEv = float( - 12.47393 );
  22712. const AgxMaxEv = float( 4.026069 );
  22713. colortone.mulAssign( exposure );
  22714. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  22715. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  22716. colortone.assign( max$1( colortone, 1e-10 ) );
  22717. colortone.assign( log2( colortone ) );
  22718. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  22719. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22720. colortone.assign( agxDefaultContrastApprox( colortone ) );
  22721. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  22722. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  22723. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  22724. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  22725. return colortone;
  22726. } ).setLayout( {
  22727. name: 'agxToneMapping',
  22728. type: 'vec3',
  22729. inputs: [
  22730. { name: 'color', type: 'vec3' },
  22731. { name: 'exposure', type: 'float' }
  22732. ]
  22733. } );
  22734. /**
  22735. * Neutral tone mapping.
  22736. *
  22737. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  22738. *
  22739. * @method
  22740. * @param {Node<vec3>} color - The color that should be tone mapped.
  22741. * @param {Node<float>} exposure - The exposure.
  22742. * @return {Node<vec3>} The tone mapped color.
  22743. */
  22744. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  22745. const StartCompression = float( 0.8 - 0.04 );
  22746. const Desaturation = float( 0.15 );
  22747. color = color.mul( exposure );
  22748. const x = min$1( color.r, min$1( color.g, color.b ) );
  22749. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  22750. color.subAssign( offset );
  22751. const peak = max$1( color.r, max$1( color.g, color.b ) );
  22752. If( peak.lessThan( StartCompression ), () => {
  22753. return color;
  22754. } );
  22755. const d = sub( 1, StartCompression );
  22756. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  22757. color.mulAssign( newPeak.div( peak ) );
  22758. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  22759. return mix( color, vec3( newPeak ), g );
  22760. } ).setLayout( {
  22761. name: 'neutralToneMapping',
  22762. type: 'vec3',
  22763. inputs: [
  22764. { name: 'color', type: 'vec3' },
  22765. { name: 'exposure', type: 'float' }
  22766. ]
  22767. } );
  22768. /** @module CodeNode **/
  22769. /**
  22770. * This class represents native code sections. It is the base
  22771. * class for modules like {@link FunctionNode} which allows to implement
  22772. * functions with native shader languages.
  22773. *
  22774. * @augments Node
  22775. */
  22776. class CodeNode extends Node {
  22777. static get type() {
  22778. return 'CodeNode';
  22779. }
  22780. /**
  22781. * Constructs a new code node.
  22782. *
  22783. * @param {String} [code=''] - The native code.
  22784. * @param {Array<Node>} [includes=[]] - An array of includes.
  22785. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22786. */
  22787. constructor( code = '', includes = [], language = '' ) {
  22788. super( 'code' );
  22789. /**
  22790. * This flag can be used for type testing.
  22791. *
  22792. * @type {Boolean}
  22793. * @readonly
  22794. * @default true
  22795. */
  22796. this.isCodeNode = true;
  22797. /**
  22798. * The native code.
  22799. *
  22800. * @type {String}
  22801. * @default ''
  22802. */
  22803. this.code = code;
  22804. /**
  22805. * An array of includes
  22806. *
  22807. * @type {Array<Node>}
  22808. * @default []
  22809. */
  22810. this.includes = includes;
  22811. /**
  22812. * The used language.
  22813. *
  22814. * @type {('js'|'wgsl'|'glsl')}
  22815. * @default ''
  22816. */
  22817. this.language = language;
  22818. }
  22819. /**
  22820. * The method is overwritten so it always returns `true`.
  22821. *
  22822. * @return {Boolean} Whether this node is global or not.
  22823. */
  22824. isGlobal() {
  22825. return true;
  22826. }
  22827. /**
  22828. * Sets the includes of this code node.
  22829. *
  22830. * @param {Array<Node>} includes - The includes to set.
  22831. * @return {CodeNode} A reference to this node.
  22832. */
  22833. setIncludes( includes ) {
  22834. this.includes = includes;
  22835. return this;
  22836. }
  22837. /**
  22838. * Returns the includes of this code node.
  22839. *
  22840. * @param {NodeBuilder} builder - The current node builder.
  22841. * @return {Array<Node>} The includes.
  22842. */
  22843. getIncludes( /*builder*/ ) {
  22844. return this.includes;
  22845. }
  22846. generate( builder ) {
  22847. const includes = this.getIncludes( builder );
  22848. for ( const include of includes ) {
  22849. include.build( builder );
  22850. }
  22851. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  22852. nodeCode.code = this.code;
  22853. return nodeCode.code;
  22854. }
  22855. serialize( data ) {
  22856. super.serialize( data );
  22857. data.code = this.code;
  22858. data.language = this.language;
  22859. }
  22860. deserialize( data ) {
  22861. super.deserialize( data );
  22862. this.code = data.code;
  22863. this.language = data.language;
  22864. }
  22865. }
  22866. /**
  22867. * TSL function for creating a code node.
  22868. *
  22869. * @function
  22870. * @param {String} [code=''] - The native code.
  22871. * @param {Array<Node>} [includes=[]] - An array of includes.
  22872. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22873. * @returns {CodeNode}
  22874. */
  22875. const code = /*@__PURE__*/ nodeProxy( CodeNode );
  22876. /**
  22877. * TSL function for creating a JS code node.
  22878. *
  22879. * @function
  22880. * @param {String} src - The native code.
  22881. * @param {Array<Node>} includes - An array of includes.
  22882. * @returns {CodeNode}
  22883. */
  22884. const js = ( src, includes ) => code( src, includes, 'js' );
  22885. /**
  22886. * TSL function for creating a WGSL code node.
  22887. *
  22888. * @function
  22889. * @param {String} src - The native code.
  22890. * @param {Array<Node>} includes - An array of includes.
  22891. * @returns {CodeNode}
  22892. */
  22893. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  22894. /**
  22895. * TSL function for creating a GLSL code node.
  22896. *
  22897. * @function
  22898. * @param {String} src - The native code.
  22899. * @param {Array<Node>} includes - An array of includes.
  22900. * @returns {CodeNode}
  22901. */
  22902. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  22903. /**
  22904. * This class represents a native shader function. It can be used to implement
  22905. * certain aspects of a node material with native shader code. There are two predefined
  22906. * TSL functions for easier usage.
  22907. *
  22908. * - `wgslFn`: Creates a WGSL function node.
  22909. * - `glslFn`: Creates a GLSL function node.
  22910. *
  22911. * A basic example with one include looks like so:
  22912. *
  22913. * ```js
  22914. * const desaturateWGSLFn = wgslFn( `
  22915. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  22916. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  22917. * return vec3<f32>( dot( lum, color ) );
  22918. * }`
  22919. *);
  22920. * const someWGSLFn = wgslFn( `
  22921. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  22922. * return desaturate( color );
  22923. * }
  22924. * `, [ desaturateWGSLFn ] );
  22925. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  22926. *```
  22927. * @augments CodeNode
  22928. */
  22929. class FunctionNode extends CodeNode {
  22930. static get type() {
  22931. return 'FunctionNode';
  22932. }
  22933. /**
  22934. * Constructs a new function node.
  22935. *
  22936. * @param {String} [code=''] - The native code.
  22937. * @param {Array<Node>} [includes=[]] - An array of includes.
  22938. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  22939. */
  22940. constructor( code = '', includes = [], language = '' ) {
  22941. super( code, includes, language );
  22942. }
  22943. getNodeType( builder ) {
  22944. return this.getNodeFunction( builder ).type;
  22945. }
  22946. /**
  22947. * Returns the inputs of this function node.
  22948. *
  22949. * @param {NodeBuilder} builder - The current node builder.
  22950. * @return {Array<NodeFunctionInput>} The inputs.
  22951. */
  22952. getInputs( builder ) {
  22953. return this.getNodeFunction( builder ).inputs;
  22954. }
  22955. /**
  22956. * Returns the node function for this function node.
  22957. *
  22958. * @param {NodeBuilder} builder - The current node builder.
  22959. * @return {NodeFunction} The node function.
  22960. */
  22961. getNodeFunction( builder ) {
  22962. const nodeData = builder.getDataFromNode( this );
  22963. let nodeFunction = nodeData.nodeFunction;
  22964. if ( nodeFunction === undefined ) {
  22965. nodeFunction = builder.parser.parseFunction( this.code );
  22966. nodeData.nodeFunction = nodeFunction;
  22967. }
  22968. return nodeFunction;
  22969. }
  22970. generate( builder, output ) {
  22971. super.generate( builder );
  22972. const nodeFunction = this.getNodeFunction( builder );
  22973. const name = nodeFunction.name;
  22974. const type = nodeFunction.type;
  22975. const nodeCode = builder.getCodeFromNode( this, type );
  22976. if ( name !== '' ) {
  22977. // use a custom property name
  22978. nodeCode.name = name;
  22979. }
  22980. const propertyName = builder.getPropertyName( nodeCode );
  22981. const code = this.getNodeFunction( builder ).getCode( propertyName );
  22982. nodeCode.code = code + '\n';
  22983. if ( output === 'property' ) {
  22984. return propertyName;
  22985. } else {
  22986. return builder.format( `${ propertyName }()`, type, output );
  22987. }
  22988. }
  22989. }
  22990. const nativeFn = ( code, includes = [], language = '' ) => {
  22991. for ( let i = 0; i < includes.length; i ++ ) {
  22992. const include = includes[ i ];
  22993. // TSL Function: glslFn, wgslFn
  22994. if ( typeof include === 'function' ) {
  22995. includes[ i ] = include.functionNode;
  22996. }
  22997. }
  22998. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  22999. const fn = ( ...params ) => functionNode.call( ...params );
  23000. fn.functionNode = functionNode;
  23001. return fn;
  23002. };
  23003. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  23004. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  23005. /** @module ScriptableValueNode **/
  23006. /**
  23007. * `ScriptableNode` uses this class to manage script inputs and outputs.
  23008. *
  23009. * @augments Node
  23010. */
  23011. class ScriptableValueNode extends Node {
  23012. static get type() {
  23013. return 'ScriptableValueNode';
  23014. }
  23015. /**
  23016. * Constructs a new scriptable node.
  23017. *
  23018. * @param {Any} [value=null] - The value.
  23019. */
  23020. constructor( value = null ) {
  23021. super();
  23022. /**
  23023. * A reference to the value.
  23024. *
  23025. * @private
  23026. * @default null
  23027. */
  23028. this._value = value;
  23029. /**
  23030. * Depending on the type of `_value`, this property might cache parsed data.
  23031. *
  23032. * @private
  23033. * @default null
  23034. */
  23035. this._cache = null;
  23036. /**
  23037. * If this node represents an input, this property represents the input type.
  23038. *
  23039. * @type {String?}
  23040. * @default null
  23041. */
  23042. this.inputType = null;
  23043. /**
  23044. * If this node represents an output, this property represents the output type.
  23045. *
  23046. * @type {String?}
  23047. * @default null
  23048. */
  23049. this.outputType = null;
  23050. /**
  23051. * An event dispatcher for managing events.
  23052. *
  23053. * @type {EventDispatcher}
  23054. */
  23055. this.events = new EventDispatcher();
  23056. /**
  23057. * This flag can be used for type testing.
  23058. *
  23059. * @type {Boolean}
  23060. * @readonly
  23061. * @default true
  23062. */
  23063. this.isScriptableValueNode = true;
  23064. }
  23065. /**
  23066. * Whether this node represents an output or not.
  23067. *
  23068. * @type {Boolean}
  23069. * @readonly
  23070. * @default true
  23071. */
  23072. get isScriptableOutputNode() {
  23073. return this.outputType !== null;
  23074. }
  23075. set value( val ) {
  23076. if ( this._value === val ) return;
  23077. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  23078. URL.revokeObjectURL( this._cache );
  23079. this._cache = null;
  23080. }
  23081. this._value = val;
  23082. this.events.dispatchEvent( { type: 'change' } );
  23083. this.refresh();
  23084. }
  23085. /**
  23086. * The node's value.
  23087. *
  23088. * @type {Any}
  23089. */
  23090. get value() {
  23091. return this._value;
  23092. }
  23093. /**
  23094. * Dispatches the `refresh` event.
  23095. */
  23096. refresh() {
  23097. this.events.dispatchEvent( { type: 'refresh' } );
  23098. }
  23099. /**
  23100. * The `value` property usually represents a node or even binary data in form of array buffers.
  23101. * In this case, this method tries to return the actual value behind the complex type.
  23102. *
  23103. * @return {Any} The value.
  23104. */
  23105. getValue() {
  23106. const value = this.value;
  23107. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  23108. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  23109. } else if ( value && value.value !== null && value.value !== undefined && (
  23110. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  23111. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  23112. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  23113. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  23114. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  23115. ( this.inputType === 'Color' && value.value.isColor ) ||
  23116. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  23117. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  23118. ) ) {
  23119. return value.value;
  23120. }
  23121. return this._cache || value;
  23122. }
  23123. /**
  23124. * Overwritten since the node type is inferred from the value.
  23125. *
  23126. * @param {NodeBuilder} builder - The current node builder.
  23127. * @return {String} The node type.
  23128. */
  23129. getNodeType( builder ) {
  23130. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  23131. }
  23132. setup() {
  23133. return this.value && this.value.isNode ? this.value : float();
  23134. }
  23135. serialize( data ) {
  23136. super.serialize( data );
  23137. if ( this.value !== null ) {
  23138. if ( this.inputType === 'ArrayBuffer' ) {
  23139. data.value = arrayBufferToBase64( this.value );
  23140. } else {
  23141. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  23142. }
  23143. } else {
  23144. data.value = null;
  23145. }
  23146. data.inputType = this.inputType;
  23147. data.outputType = this.outputType;
  23148. }
  23149. deserialize( data ) {
  23150. super.deserialize( data );
  23151. let value = null;
  23152. if ( data.value !== null ) {
  23153. if ( data.inputType === 'ArrayBuffer' ) {
  23154. value = base64ToArrayBuffer( data.value );
  23155. } else if ( data.inputType === 'Texture' ) {
  23156. value = data.meta.textures[ data.value ];
  23157. } else {
  23158. value = data.meta.nodes[ data.value ] || null;
  23159. }
  23160. }
  23161. this.value = value;
  23162. this.inputType = data.inputType;
  23163. this.outputType = data.outputType;
  23164. }
  23165. }
  23166. /**
  23167. * TSL function for creating a scriptable value node.
  23168. *
  23169. * @function
  23170. * @param {Any} [value=null] - The value.
  23171. * @returns {ScriptableValueNode}
  23172. */
  23173. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode );
  23174. /** @module ScriptableNode **/
  23175. /**
  23176. * A Map-like data structure for managing resources of scriptable nodes.
  23177. *
  23178. * @augments Map
  23179. */
  23180. class Resources extends Map {
  23181. get( key, callback = null, ...params ) {
  23182. if ( this.has( key ) ) return super.get( key );
  23183. if ( callback !== null ) {
  23184. const value = callback( ...params );
  23185. this.set( key, value );
  23186. return value;
  23187. }
  23188. }
  23189. }
  23190. class Parameters {
  23191. constructor( scriptableNode ) {
  23192. this.scriptableNode = scriptableNode;
  23193. }
  23194. get parameters() {
  23195. return this.scriptableNode.parameters;
  23196. }
  23197. get layout() {
  23198. return this.scriptableNode.getLayout();
  23199. }
  23200. getInputLayout( id ) {
  23201. return this.scriptableNode.getInputLayout( id );
  23202. }
  23203. get( name ) {
  23204. const param = this.parameters[ name ];
  23205. const value = param ? param.getValue() : null;
  23206. return value;
  23207. }
  23208. }
  23209. /**
  23210. * Defines the resources (e.g. namespaces) of scriptable nodes.
  23211. *
  23212. * @type {Resources}
  23213. */
  23214. const ScriptableNodeResources = new Resources();
  23215. /**
  23216. * This type of node allows to implement nodes with custom scripts. The script
  23217. * section is represented as an instance of `CodeNode` written with JavaScript.
  23218. * The script itself must adhere to a specific structure.
  23219. *
  23220. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  23221. * - layout: The layout object defines the script's interface (inputs and outputs).
  23222. *
  23223. * ```js
  23224. * ScriptableNodeResources.set( 'TSL', TSL );
  23225. *
  23226. * const scriptableNode = scriptable( js( `
  23227. * layout = {
  23228. * outputType: 'node',
  23229. * elements: [
  23230. * { name: 'source', inputType: 'node' },
  23231. * ]
  23232. * };
  23233. *
  23234. * const { mul, oscSine } = TSL;
  23235. *
  23236. * function main() {
  23237. * const source = parameters.get( 'source' ) || float();
  23238. * return mul( source, oscSine() ) );
  23239. * }
  23240. *
  23241. * ` ) );
  23242. *
  23243. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  23244. *
  23245. * const material = new THREE.MeshBasicNodeMaterial();
  23246. * material.colorNode = scriptableNode;
  23247. * ```
  23248. *
  23249. * @augments Node
  23250. */
  23251. class ScriptableNode extends Node {
  23252. static get type() {
  23253. return 'ScriptableNode';
  23254. }
  23255. /**
  23256. * Constructs a new scriptable node.
  23257. *
  23258. * @param {CodeNode?} [codeNode=null] - The code node.
  23259. * @param {Object} [parameters={}] - The parameters definition.
  23260. */
  23261. constructor( codeNode = null, parameters = {} ) {
  23262. super();
  23263. /**
  23264. * The code node.
  23265. *
  23266. * @type {CodeNode?}
  23267. * @default null
  23268. */
  23269. this.codeNode = codeNode;
  23270. /**
  23271. * The parameters definition.
  23272. *
  23273. * @type {Object}
  23274. * @default {}
  23275. */
  23276. this.parameters = parameters;
  23277. this._local = new Resources();
  23278. this._output = scriptableValue();
  23279. this._outputs = {};
  23280. this._source = this.source;
  23281. this._method = null;
  23282. this._object = null;
  23283. this._value = null;
  23284. this._needsOutputUpdate = true;
  23285. this.onRefresh = this.onRefresh.bind( this );
  23286. /**
  23287. * This flag can be used for type testing.
  23288. *
  23289. * @type {Boolean}
  23290. * @readonly
  23291. * @default true
  23292. */
  23293. this.isScriptableNode = true;
  23294. }
  23295. /**
  23296. * The source code of the scriptable node.
  23297. *
  23298. * @type {String}
  23299. */
  23300. get source() {
  23301. return this.codeNode ? this.codeNode.code : '';
  23302. }
  23303. /**
  23304. * Sets the reference of a local script variable.
  23305. *
  23306. * @param {String} name - The variable name.
  23307. * @param {Object} value - The reference to set.
  23308. * @return {Resources} The resource map
  23309. */
  23310. setLocal( name, value ) {
  23311. return this._local.set( name, value );
  23312. }
  23313. /**
  23314. * Gets the value of a local script variable.
  23315. *
  23316. * @param {String} name - The variable name.
  23317. * @return {Object} The value.
  23318. */
  23319. getLocal( name ) {
  23320. return this._local.get( name );
  23321. }
  23322. /**
  23323. * Event listener for the `refresh` event.
  23324. */
  23325. onRefresh() {
  23326. this._refresh();
  23327. }
  23328. /**
  23329. * Returns an input from the layout with the given id/name.
  23330. *
  23331. * @param {String} id - The id/name of the input.
  23332. * @return {Object} The element entry.
  23333. */
  23334. getInputLayout( id ) {
  23335. for ( const element of this.getLayout() ) {
  23336. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  23337. return element;
  23338. }
  23339. }
  23340. }
  23341. /**
  23342. * Returns an output from the layout with the given id/name.
  23343. *
  23344. * @param {String} id - The id/name of the output.
  23345. * @return {Object} The element entry.
  23346. */
  23347. getOutputLayout( id ) {
  23348. for ( const element of this.getLayout() ) {
  23349. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  23350. return element;
  23351. }
  23352. }
  23353. }
  23354. /**
  23355. * Defines a script output for the given name and value.
  23356. *
  23357. * @param {String} name - The name of the output.
  23358. * @param {Node} value - The node value.
  23359. * @return {ScriptableNode} A reference to this node.
  23360. */
  23361. setOutput( name, value ) {
  23362. const outputs = this._outputs;
  23363. if ( outputs[ name ] === undefined ) {
  23364. outputs[ name ] = scriptableValue( value );
  23365. } else {
  23366. outputs[ name ].value = value;
  23367. }
  23368. return this;
  23369. }
  23370. /**
  23371. * Returns a script output for the given name.
  23372. *
  23373. * @param {String} name - The name of the output.
  23374. * @return {ScriptableValueNode} The node value.
  23375. */
  23376. getOutput( name ) {
  23377. return this._outputs[ name ];
  23378. }
  23379. /**
  23380. * Returns a parameter for the given name
  23381. *
  23382. * @param {String} name - The name of the parameter.
  23383. * @return {ScriptableValueNode} The node value.
  23384. */
  23385. getParameter( name ) {
  23386. return this.parameters[ name ];
  23387. }
  23388. /**
  23389. * Sets a value for the given parameter name.
  23390. *
  23391. * @param {String} name - The parameter name.
  23392. * @param {Any} value - The parameter value.
  23393. * @return {ScriptableNode} A reference to this node.
  23394. */
  23395. setParameter( name, value ) {
  23396. const parameters = this.parameters;
  23397. if ( value && value.isScriptableNode ) {
  23398. this.deleteParameter( name );
  23399. parameters[ name ] = value;
  23400. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  23401. } else if ( value && value.isScriptableValueNode ) {
  23402. this.deleteParameter( name );
  23403. parameters[ name ] = value;
  23404. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23405. } else if ( parameters[ name ] === undefined ) {
  23406. parameters[ name ] = scriptableValue( value );
  23407. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  23408. } else {
  23409. parameters[ name ].value = value;
  23410. }
  23411. return this;
  23412. }
  23413. /**
  23414. * Returns the value of this node which is the value of
  23415. * the default output.
  23416. *
  23417. * @return {Node} The value.
  23418. */
  23419. getValue() {
  23420. return this.getDefaultOutput().getValue();
  23421. }
  23422. /**
  23423. * Deletes a parameter from the script.
  23424. *
  23425. * @param {String} name - The parameter to remove.
  23426. * @return {ScriptableNode} A reference to this node.
  23427. */
  23428. deleteParameter( name ) {
  23429. let valueNode = this.parameters[ name ];
  23430. if ( valueNode ) {
  23431. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23432. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  23433. }
  23434. return this;
  23435. }
  23436. /**
  23437. * Deletes all parameters from the script.
  23438. *
  23439. * @return {ScriptableNode} A reference to this node.
  23440. */
  23441. clearParameters() {
  23442. for ( const name of Object.keys( this.parameters ) ) {
  23443. this.deleteParameter( name );
  23444. }
  23445. this.needsUpdate = true;
  23446. return this;
  23447. }
  23448. /**
  23449. * Calls a function from the script.
  23450. *
  23451. * @param {String} name - The function name.
  23452. * @param {...Any} params - A list of parameters.
  23453. * @return {Any} The result of the function call.
  23454. */
  23455. call( name, ...params ) {
  23456. const object = this.getObject();
  23457. const method = object[ name ];
  23458. if ( typeof method === 'function' ) {
  23459. return method( ...params );
  23460. }
  23461. }
  23462. /**
  23463. * Asynchronously calls a function from the script.
  23464. *
  23465. * @param {String} name - The function name.
  23466. * @param {...Any} params - A list of parameters.
  23467. * @return {Promise<Any>} The result of the function call.
  23468. */
  23469. async callAsync( name, ...params ) {
  23470. const object = this.getObject();
  23471. const method = object[ name ];
  23472. if ( typeof method === 'function' ) {
  23473. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  23474. }
  23475. }
  23476. /**
  23477. * Overwritten since the node types is inferred from the script's output.
  23478. *
  23479. * @param {NodeBuilder} builder - The current node builder
  23480. * @return {String} The node type.
  23481. */
  23482. getNodeType( builder ) {
  23483. return this.getDefaultOutputNode().getNodeType( builder );
  23484. }
  23485. /**
  23486. * Refreshes the script node.
  23487. *
  23488. * @param {String?} [output=null] - An optional output.
  23489. */
  23490. refresh( output = null ) {
  23491. if ( output !== null ) {
  23492. this.getOutput( output ).refresh();
  23493. } else {
  23494. this._refresh();
  23495. }
  23496. }
  23497. /**
  23498. * Returns an object representation of the script.
  23499. *
  23500. * @return {Object} The result object.
  23501. */
  23502. getObject() {
  23503. if ( this.needsUpdate ) this.dispose();
  23504. if ( this._object !== null ) return this._object;
  23505. //
  23506. const refresh = () => this.refresh();
  23507. const setOutput = ( id, value ) => this.setOutput( id, value );
  23508. const parameters = new Parameters( this );
  23509. const THREE = ScriptableNodeResources.get( 'THREE' );
  23510. const TSL = ScriptableNodeResources.get( 'TSL' );
  23511. const method = this.getMethod();
  23512. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  23513. this._object = method( ...params );
  23514. const layout = this._object.layout;
  23515. if ( layout ) {
  23516. if ( layout.cache === false ) {
  23517. this._local.clear();
  23518. }
  23519. // default output
  23520. this._output.outputType = layout.outputType || null;
  23521. if ( Array.isArray( layout.elements ) ) {
  23522. for ( const element of layout.elements ) {
  23523. const id = element.id || element.name;
  23524. if ( element.inputType ) {
  23525. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  23526. this.getParameter( id ).inputType = element.inputType;
  23527. }
  23528. if ( element.outputType ) {
  23529. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  23530. this.getOutput( id ).outputType = element.outputType;
  23531. }
  23532. }
  23533. }
  23534. }
  23535. return this._object;
  23536. }
  23537. deserialize( data ) {
  23538. super.deserialize( data );
  23539. for ( const name in this.parameters ) {
  23540. let valueNode = this.parameters[ name ];
  23541. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  23542. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  23543. }
  23544. }
  23545. /**
  23546. * Returns the layout of the script.
  23547. *
  23548. * @return {Object} The script's layout.
  23549. */
  23550. getLayout() {
  23551. return this.getObject().layout;
  23552. }
  23553. /**
  23554. * Returns default node output of the script.
  23555. *
  23556. * @return {Node} The default node output.
  23557. */
  23558. getDefaultOutputNode() {
  23559. const output = this.getDefaultOutput().value;
  23560. if ( output && output.isNode ) {
  23561. return output;
  23562. }
  23563. return float();
  23564. }
  23565. /**
  23566. * Returns default output of the script.
  23567. *
  23568. * @return {ScriptableValueNode} The default output.
  23569. */
  23570. getDefaultOutput() {
  23571. return this._exec()._output;
  23572. }
  23573. /**
  23574. * Returns a function created from the node's script.
  23575. *
  23576. * @return {Function} The function representing the node's code.
  23577. */
  23578. getMethod() {
  23579. if ( this.needsUpdate ) this.dispose();
  23580. if ( this._method !== null ) return this._method;
  23581. //
  23582. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  23583. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  23584. const properties = interfaceProps.join( ', ' );
  23585. const declarations = 'var ' + properties + '; var output = {};\n';
  23586. const returns = '\nreturn { ...output, ' + properties + ' };';
  23587. const code = declarations + this.codeNode.code + returns;
  23588. //
  23589. this._method = new Function( ...parametersProps, code );
  23590. return this._method;
  23591. }
  23592. /**
  23593. * Frees all internal resources.
  23594. */
  23595. dispose() {
  23596. if ( this._method === null ) return;
  23597. if ( this._object && typeof this._object.dispose === 'function' ) {
  23598. this._object.dispose();
  23599. }
  23600. this._method = null;
  23601. this._object = null;
  23602. this._source = null;
  23603. this._value = null;
  23604. this._needsOutputUpdate = true;
  23605. this._output.value = null;
  23606. this._outputs = {};
  23607. }
  23608. setup() {
  23609. return this.getDefaultOutputNode();
  23610. }
  23611. getCacheKey( force ) {
  23612. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  23613. for ( const param in this.parameters ) {
  23614. values.push( this.parameters[ param ].getCacheKey( force ) );
  23615. }
  23616. return hashArray( values );
  23617. }
  23618. set needsUpdate( value ) {
  23619. if ( value === true ) this.dispose();
  23620. }
  23621. get needsUpdate() {
  23622. return this.source !== this._source;
  23623. }
  23624. /**
  23625. * Executes the `main` function of the script.
  23626. *
  23627. * @private
  23628. * @return {ScriptableNode} A reference to this node.
  23629. */
  23630. _exec() {
  23631. if ( this.codeNode === null ) return this;
  23632. if ( this._needsOutputUpdate === true ) {
  23633. this._value = this.call( 'main' );
  23634. this._needsOutputUpdate = false;
  23635. }
  23636. this._output.value = this._value;
  23637. return this;
  23638. }
  23639. /**
  23640. * Executes the refresh.
  23641. *
  23642. * @private
  23643. */
  23644. _refresh() {
  23645. this.needsUpdate = true;
  23646. this._exec();
  23647. this._output.refresh();
  23648. }
  23649. }
  23650. /**
  23651. * TSL function for creating a scriptable node.
  23652. *
  23653. * @function
  23654. * @param {CodeNode?} [codeNode=null] - The code node.
  23655. * @param {Object} [parameters={}] - The parameters definition.
  23656. * @returns {ScriptableNode}
  23657. */
  23658. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode );
  23659. /** @module Fog **/
  23660. /**
  23661. * Returns a node that represents the `z` coordinate in view space
  23662. * for the current fragment. It's a different representation of the
  23663. * default depth value.
  23664. *
  23665. * This value can be part of a computation that defines how the fog
  23666. * density increases when moving away from the camera.
  23667. *
  23668. * @param {NodeBuilder} builder - The current node builder.
  23669. * @return {Node} The viewZ node.
  23670. */
  23671. function getViewZNode( builder ) {
  23672. let viewZ;
  23673. const getViewZ = builder.context.getViewZ;
  23674. if ( getViewZ !== undefined ) {
  23675. viewZ = getViewZ( this );
  23676. }
  23677. return ( viewZ || positionView.z ).negate();
  23678. }
  23679. /**
  23680. * Constructs a new range factor node.
  23681. *
  23682. * @function
  23683. * @param {Node} near - Defines the near value.
  23684. * @param {Node} far - Defines the far value.
  23685. */
  23686. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  23687. const viewZ = getViewZNode( builder );
  23688. return smoothstep( near, far, viewZ );
  23689. } );
  23690. /**
  23691. * Represents an exponential squared fog. This type of fog gives
  23692. * a clear view near the camera and a faster than exponentially
  23693. * densening fog farther from the camera.
  23694. *
  23695. * @function
  23696. * @param {Node} density - Defines the fog density.
  23697. */
  23698. const densityFogFactor = Fn( ( [ density ], builder ) => {
  23699. const viewZ = getViewZNode( builder );
  23700. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  23701. } );
  23702. /**
  23703. * This class can be used to configure a fog for the scene.
  23704. * Nodes of this type are assigned to `Scene.fogNode`.
  23705. *
  23706. * @function
  23707. * @param {Node} color - Defines the color of the fog.
  23708. * @param {Node} factor - Defines how the fog is factored in the scene.
  23709. */
  23710. const fog = Fn( ( [ color, factor ] ) => {
  23711. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  23712. } );
  23713. // Deprecated
  23714. /**
  23715. * @function
  23716. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  23717. *
  23718. * @param {Node} color
  23719. * @param {Node} near
  23720. * @param {Node} far
  23721. * @returns {Function}
  23722. */
  23723. function rangeFog( color, near, far ) { // @deprecated, r171
  23724. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  23725. return fog( color, rangeFogFactor( near, far ) );
  23726. }
  23727. /**
  23728. * @function
  23729. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  23730. *
  23731. * @param {Node} color
  23732. * @param {Node} density
  23733. * @returns {Function}
  23734. */
  23735. function densityFog( color, density ) { // @deprecated, r171
  23736. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  23737. return fog( color, densityFogFactor( density ) );
  23738. }
  23739. /** @module RangeNode **/
  23740. let min = null;
  23741. let max = null;
  23742. /**
  23743. * `RangeNode` generates random instanced attribute data in a defined range.
  23744. * An exemplary use case for this utility node is to generate random per-instance
  23745. * colors:
  23746. * ```js
  23747. * const material = new MeshBasicNodeMaterial();
  23748. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  23749. * const mesh = new InstancedMesh( geometry, material, count );
  23750. * ```
  23751. * @augments Node
  23752. */
  23753. class RangeNode extends Node {
  23754. static get type() {
  23755. return 'RangeNode';
  23756. }
  23757. /**
  23758. * Constructs a new range node.
  23759. *
  23760. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23761. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23762. */
  23763. constructor( minNode = float(), maxNode = float() ) {
  23764. super();
  23765. /**
  23766. * A node defining the lower bound of the range.
  23767. *
  23768. * @type {Node<any>}
  23769. * @default float()
  23770. */
  23771. this.minNode = minNode;
  23772. /**
  23773. * A node defining the upper bound of the range.
  23774. *
  23775. * @type {Node<any>}
  23776. * @default float()
  23777. */
  23778. this.maxNode = maxNode;
  23779. }
  23780. /**
  23781. * Returns the vector length which is computed based on the range definition.
  23782. *
  23783. * @param {NodeBuilder} builder - The current node builder.
  23784. * @return {Number} The vector length.
  23785. */
  23786. getVectorLength( builder ) {
  23787. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  23788. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  23789. return minLength > maxLength ? minLength : maxLength;
  23790. }
  23791. /**
  23792. * This method is overwritten since the node type is inferred from range definition.
  23793. *
  23794. * @param {NodeBuilder} builder - The current node builder.
  23795. * @return {String} The node type.
  23796. */
  23797. getNodeType( builder ) {
  23798. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  23799. }
  23800. setup( builder ) {
  23801. const object = builder.object;
  23802. let output = null;
  23803. if ( object.count > 1 ) {
  23804. const minValue = this.minNode.value;
  23805. const maxValue = this.maxNode.value;
  23806. const minLength = builder.getTypeLength( getValueType( minValue ) );
  23807. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  23808. min = min || new Vector4();
  23809. max = max || new Vector4();
  23810. min.setScalar( 0 );
  23811. max.setScalar( 0 );
  23812. if ( minLength === 1 ) min.setScalar( minValue );
  23813. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  23814. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  23815. if ( maxLength === 1 ) max.setScalar( maxValue );
  23816. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  23817. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  23818. const stride = 4;
  23819. const length = stride * object.count;
  23820. const array = new Float32Array( length );
  23821. for ( let i = 0; i < length; i ++ ) {
  23822. const index = i % stride;
  23823. const minElementValue = min.getComponent( index );
  23824. const maxElementValue = max.getComponent( index );
  23825. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  23826. }
  23827. const nodeType = this.getNodeType( builder );
  23828. if ( object.count <= 4096 ) {
  23829. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  23830. } else {
  23831. // TODO: Improve anonymous buffer attribute creation removing this part
  23832. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  23833. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  23834. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  23835. }
  23836. } else {
  23837. output = float( 0 );
  23838. }
  23839. return output;
  23840. }
  23841. }
  23842. /**
  23843. * TSL function for creating a range node.
  23844. *
  23845. * @function
  23846. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  23847. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  23848. * @returns {RangeNode}
  23849. */
  23850. const range = /*@__PURE__*/ nodeProxy( RangeNode );
  23851. /** @module ComputeBuiltinNode **/
  23852. /**
  23853. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  23854. * about the currently running dispatch and/or the device it is running on.
  23855. *
  23856. * This node can only be used with a WebGPU backend.
  23857. *
  23858. * @augments Node
  23859. */
  23860. class ComputeBuiltinNode extends Node {
  23861. static get type() {
  23862. return 'ComputeBuiltinNode';
  23863. }
  23864. /**
  23865. * Constructs a new compute builtin node.
  23866. *
  23867. * @param {String} builtinName - The built-in name.
  23868. * @param {String} nodeType - The node type.
  23869. */
  23870. constructor( builtinName, nodeType ) {
  23871. super( nodeType );
  23872. /**
  23873. * The built-in name.
  23874. *
  23875. * @private
  23876. * @type {String}
  23877. */
  23878. this._builtinName = builtinName;
  23879. }
  23880. /**
  23881. * This method is overwritten since hash is derived from the built-in name.
  23882. *
  23883. * @param {NodeBuilder} builder - The current node builder.
  23884. * @return {String} The hash.
  23885. */
  23886. getHash( builder ) {
  23887. return this.getBuiltinName( builder );
  23888. }
  23889. /**
  23890. * This method is overwritten since the node type is simply derived from `nodeType`..
  23891. *
  23892. * @param {NodeBuilder} builder - The current node builder.
  23893. * @return {String} The node type.
  23894. */
  23895. getNodeType( /*builder*/ ) {
  23896. return this.nodeType;
  23897. }
  23898. /**
  23899. * Sets the builtin name.
  23900. *
  23901. * @param {String} builtinName - The built-in name.
  23902. * @return {ComputeBuiltinNode} A reference to this node.
  23903. */
  23904. setBuiltinName( builtinName ) {
  23905. this._builtinName = builtinName;
  23906. return this;
  23907. }
  23908. /**
  23909. * Returns the builtin name.
  23910. *
  23911. * @param {NodeBuilder} builder - The current node builder.
  23912. * @return {String} The builtin name.
  23913. */
  23914. getBuiltinName( /*builder*/ ) {
  23915. return this._builtinName;
  23916. }
  23917. /**
  23918. * Whether the current node builder has the builtin or not.
  23919. *
  23920. * @param {NodeBuilder} builder - The current node builder.
  23921. */
  23922. hasBuiltin( builder ) {
  23923. builder.hasBuiltin( this._builtinName );
  23924. }
  23925. generate( builder, output ) {
  23926. const builtinName = this.getBuiltinName( builder );
  23927. const nodeType = this.getNodeType( builder );
  23928. if ( builder.shaderStage === 'compute' ) {
  23929. return builder.format( builtinName, nodeType, output );
  23930. } else {
  23931. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  23932. return builder.generateConst( nodeType );
  23933. }
  23934. }
  23935. serialize( data ) {
  23936. super.serialize( data );
  23937. data.global = this.global;
  23938. data._builtinName = this._builtinName;
  23939. }
  23940. deserialize( data ) {
  23941. super.deserialize( data );
  23942. this.global = data.global;
  23943. this._builtinName = data._builtinName;
  23944. }
  23945. }
  23946. /**
  23947. * TSL function for creating a compute builtin node.
  23948. *
  23949. * @function
  23950. * @param {String} name - The built-in name.
  23951. * @param {String} nodeType - The node type.
  23952. * @returns {ComputeBuiltinNode}
  23953. */
  23954. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  23955. /**
  23956. * TSL function for creating a `numWorkgroups` builtin node.
  23957. * Represents the number of workgroups dispatched by the compute shader.
  23958. * ```js
  23959. * // Run 512 invocations/threads with a workgroup size of 128.
  23960. * const computeFn = Fn(() => {
  23961. *
  23962. * // numWorkgroups.x = 4
  23963. * storageBuffer.element(0).assign(numWorkgroups.x)
  23964. *
  23965. * })().compute(512, [128]);
  23966. *
  23967. * // Run 512 invocations/threads with the default workgroup size of 64.
  23968. * const computeFn = Fn(() => {
  23969. *
  23970. * // numWorkgroups.x = 8
  23971. * storageBuffer.element(0).assign(numWorkgroups.x)
  23972. *
  23973. * })().compute(512);
  23974. * ```
  23975. *
  23976. * @function
  23977. * @returns {ComputeBuiltinNode<uvec3>}
  23978. */
  23979. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  23980. /**
  23981. * TSL function for creating a `workgroupId` builtin node.
  23982. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  23983. * ```js
  23984. * // Execute 12 compute threads with a workgroup size of 3.
  23985. * const computeFn = Fn( () => {
  23986. *
  23987. * If( workgroupId.x.modInt( 2 ).equal( 0 ), () => {
  23988. *
  23989. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  23990. *
  23991. * } ).Else( () => {
  23992. *
  23993. * storageBuffer.element( instanceIndex ).assign( 0 );
  23994. *
  23995. * } );
  23996. *
  23997. * } )().compute( 12, [ 3 ] );
  23998. *
  23999. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  24000. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  24001. * ```
  24002. *
  24003. * @function
  24004. * @returns {ComputeBuiltinNode<uvec3>}
  24005. */
  24006. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  24007. /**
  24008. * TSL function for creating a `globalId` builtin node. A non-linearized 3-dimensional
  24009. * representation of the current invocation's position within a 3D global grid.
  24010. *
  24011. * @function
  24012. * @returns {ComputeBuiltinNode<uvec3>}
  24013. */
  24014. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  24015. /**
  24016. * TSL function for creating a `localId` builtin node. A non-linearized 3-dimensional
  24017. * representation of the current invocation's position within a 3D workgroup grid.
  24018. *
  24019. * @function
  24020. * @returns {ComputeBuiltinNode<uvec3>}
  24021. */
  24022. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  24023. /**
  24024. * TSL function for creating a `subgroupSize` builtin node. A device dependent variable
  24025. * that exposes the size of the current invocation's subgroup.
  24026. *
  24027. * @function
  24028. * @returns {ComputeBuiltinNode<uint>}
  24029. */
  24030. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  24031. /** @module BarrierNode **/
  24032. /**
  24033. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  24034. *
  24035. * This node can only be used with a WebGPU backend.
  24036. *
  24037. * @augments Node
  24038. */
  24039. class BarrierNode extends Node {
  24040. /**
  24041. * Constructs a new barrier node.
  24042. *
  24043. * @param {String} scope - The scope defines the behavior of the node.
  24044. */
  24045. constructor( scope ) {
  24046. super();
  24047. this.scope = scope;
  24048. }
  24049. generate( builder ) {
  24050. const { scope } = this;
  24051. const { renderer } = builder;
  24052. if ( renderer.backend.isWebGLBackend === true ) {
  24053. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  24054. } else {
  24055. builder.addLineFlowCode( `${scope}Barrier()`, this );
  24056. }
  24057. }
  24058. }
  24059. /**
  24060. * TSL function for creating a barrier node.
  24061. *
  24062. * @function
  24063. * @param {String} scope - The scope defines the behavior of the node..
  24064. * @returns {BarrierNode}
  24065. */
  24066. const barrier = nodeProxy( BarrierNode );
  24067. /**
  24068. * TSL function for creating a workgroup barrier. All compute shader
  24069. * invocations must wait for each invocation within a workgroup to
  24070. * complete before the barrier can be surpassed.
  24071. *
  24072. * @function
  24073. * @returns {BarrierNode}
  24074. */
  24075. const workgroupBarrier = () => barrier( 'workgroup' ).append();
  24076. /**
  24077. * TSL function for creating a storage barrier. All invocations must
  24078. * wait for each access to variables within the 'storage' address space
  24079. * to complete before the barrier can be passed.
  24080. *
  24081. * @function
  24082. * @returns {BarrierNode}
  24083. */
  24084. const storageBarrier = () => barrier( 'storage' ).append();
  24085. /**
  24086. * TSL function for creating a texture barrier. All invocations must
  24087. * wait for each access to variables within the 'texture' address space
  24088. * to complete before the barrier can be passed.
  24089. *
  24090. * @function
  24091. * @returns {BarrierNode}
  24092. */
  24093. const textureBarrier = () => barrier( 'texture' ).append();
  24094. /** @module WorkgroupInfoNode **/
  24095. /**
  24096. * Represents an element of a 'workgroup' scoped buffer.
  24097. *
  24098. * @augments ArrayElementNode
  24099. */
  24100. class WorkgroupInfoElementNode extends ArrayElementNode {
  24101. /**
  24102. * Constructs a new workgroup info element node.
  24103. *
  24104. * @param {Node} workgroupInfoNode - The workgroup info node.
  24105. * @param {Node} indexNode - The index node that defines the element access.
  24106. */
  24107. constructor( workgroupInfoNode, indexNode ) {
  24108. super( workgroupInfoNode, indexNode );
  24109. /**
  24110. * This flag can be used for type testing.
  24111. *
  24112. * @type {Boolean}
  24113. * @readonly
  24114. * @default true
  24115. */
  24116. this.isWorkgroupInfoElementNode = true;
  24117. }
  24118. generate( builder, output ) {
  24119. let snippet;
  24120. const isAssignContext = builder.context.assign;
  24121. snippet = super.generate( builder );
  24122. if ( isAssignContext !== true ) {
  24123. const type = this.getNodeType( builder );
  24124. snippet = builder.format( snippet, type, output );
  24125. }
  24126. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  24127. return snippet;
  24128. }
  24129. }
  24130. /**
  24131. * A node allowing the user to create a 'workgroup' scoped buffer within the
  24132. * context of a compute shader. Typically, workgroup scoped buffers are
  24133. * created to hold data that is transferred from a global storage scope into
  24134. * a local workgroup scope. For invocations within a workgroup, data
  24135. * access speeds on 'workgroup' scoped buffers can be significantly faster
  24136. * than similar access operations on globally accessible storage buffers.
  24137. *
  24138. * This node can only be used with a WebGPU backend.
  24139. *
  24140. * @augments Node
  24141. */
  24142. class WorkgroupInfoNode extends Node {
  24143. /**
  24144. * Constructs a new buffer scoped to type scope.
  24145. *
  24146. * @param {String} scope - TODO.
  24147. * @param {String} bufferType - The data type of a 'workgroup' scoped buffer element.
  24148. * @param {Number} [bufferCount=0] - The number of elements in the buffer.
  24149. */
  24150. constructor( scope, bufferType, bufferCount = 0 ) {
  24151. super( bufferType );
  24152. /**
  24153. * The buffer type.
  24154. *
  24155. * @type {String}
  24156. */
  24157. this.bufferType = bufferType;
  24158. /**
  24159. * The buffer count.
  24160. *
  24161. * @type {Number}
  24162. * @default 0
  24163. */
  24164. this.bufferCount = bufferCount;
  24165. /**
  24166. * This flag can be used for type testing.
  24167. *
  24168. * @type {Boolean}
  24169. * @readonly
  24170. * @default true
  24171. */
  24172. this.isWorkgroupInfoNode = true;
  24173. /**
  24174. * The data type of the array buffer.
  24175. *
  24176. * @type {String}
  24177. */
  24178. this.elementType = bufferType;
  24179. /**
  24180. * TODO.
  24181. *
  24182. * @type {String}
  24183. */
  24184. this.scope = scope;
  24185. }
  24186. /**
  24187. * Sets the name/label of this node.
  24188. *
  24189. * @param {String} name - The name to set.
  24190. * @return {WorkgroupInfoNode} A reference to this node.
  24191. */
  24192. label( name ) {
  24193. this.name = name;
  24194. return this;
  24195. }
  24196. /**
  24197. * Sets the scope of this node.
  24198. *
  24199. * @param {String} scope - The scope to set.
  24200. * @return {WorkgroupInfoNode} A reference to this node.
  24201. */
  24202. setScope( scope ) {
  24203. this.scope = scope;
  24204. return this;
  24205. }
  24206. /**
  24207. * The data type of the array buffer.
  24208. *
  24209. * @return {String} The element type.
  24210. */
  24211. getElementType() {
  24212. return this.elementType;
  24213. }
  24214. /**
  24215. * Overwrites the default implementation since the input type
  24216. * is inferred from the scope.
  24217. *
  24218. * @param {NodeBuilder} builder - The current node builder.
  24219. * @return {String} The input type.
  24220. */
  24221. getInputType( /*builder*/ ) {
  24222. return `${this.scope}Array`;
  24223. }
  24224. /**
  24225. * This method can be used to access elements via an index node.
  24226. *
  24227. * @param {IndexNode} indexNode - indexNode.
  24228. * @return {WorkgroupInfoElementNode} A reference to an element.
  24229. */
  24230. element( indexNode ) {
  24231. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  24232. }
  24233. generate( builder ) {
  24234. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  24235. }
  24236. }
  24237. /**
  24238. * TSL function for creating a workgroup info node.
  24239. * Creates a new 'workgroup' scoped array buffer.
  24240. *
  24241. * @function
  24242. * @param {String} type - The data type of a 'workgroup' scoped buffer element.
  24243. * @param {Number} [count=0] - The number of elements in the buffer.
  24244. * @returns {WorkgroupInfoNode}
  24245. */
  24246. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  24247. /** @module AtomicFunctionNode **/
  24248. /**
  24249. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  24250. * within a shader. In an atomic function, any modification to an atomic variable will
  24251. * occur as an indivisible step with a defined order relative to other modifications.
  24252. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  24253. * atomic operations will not interfere with each other.
  24254. *
  24255. * This node can only be used with a WebGPU backend.
  24256. *
  24257. * @augments TempNode
  24258. */
  24259. class AtomicFunctionNode extends TempNode {
  24260. static get type() {
  24261. return 'AtomicFunctionNode';
  24262. }
  24263. /**
  24264. * Constructs a new atomic function node.
  24265. *
  24266. * @param {String} method - The signature of the atomic function to construct.
  24267. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24268. * @param {Node} valueNode - The value that mutates the atomic variable.
  24269. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24270. */
  24271. constructor( method, pointerNode, valueNode, storeNode = null ) {
  24272. super( 'uint' );
  24273. /**
  24274. * The signature of the atomic function to construct.
  24275. *
  24276. * @type {String}
  24277. */
  24278. this.method = method;
  24279. /**
  24280. * An atomic variable or element of an atomic buffer.
  24281. *
  24282. * @type {Node}
  24283. */
  24284. this.pointerNode = pointerNode;
  24285. /**
  24286. * A value that modifies the atomic variable.
  24287. *
  24288. * @type {Node}
  24289. */
  24290. this.valueNode = valueNode;
  24291. /**
  24292. * A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24293. *
  24294. * @type {Node?}
  24295. * @default null
  24296. */
  24297. this.storeNode = storeNode;
  24298. }
  24299. /**
  24300. * Overwrites the default implementation to return the type of
  24301. * the pointer node.
  24302. *
  24303. * @param {NodeBuilder} builder - The current node builder.
  24304. * @return {String} The input type.
  24305. */
  24306. getInputType( builder ) {
  24307. return this.pointerNode.getNodeType( builder );
  24308. }
  24309. /**
  24310. * Overwritten since the node type is inferred from the input type.
  24311. *
  24312. * @param {NodeBuilder} builder - The current node builder.
  24313. * @return {String} The node type.
  24314. */
  24315. getNodeType( builder ) {
  24316. return this.getInputType( builder );
  24317. }
  24318. generate( builder ) {
  24319. const method = this.method;
  24320. const type = this.getNodeType( builder );
  24321. const inputType = this.getInputType( builder );
  24322. const a = this.pointerNode;
  24323. const b = this.valueNode;
  24324. const params = [];
  24325. params.push( `&${ a.build( builder, inputType ) }` );
  24326. params.push( b.build( builder, inputType ) );
  24327. const methodSnippet = `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`;
  24328. if ( this.storeNode !== null ) {
  24329. const varSnippet = this.storeNode.build( builder, inputType );
  24330. builder.addLineFlowCode( `${varSnippet} = ${methodSnippet}`, this );
  24331. } else {
  24332. builder.addLineFlowCode( methodSnippet, this );
  24333. }
  24334. }
  24335. }
  24336. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  24337. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  24338. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  24339. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  24340. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  24341. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  24342. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  24343. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  24344. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  24345. /**
  24346. * TSL function for creating an atomic function node.
  24347. *
  24348. * @function
  24349. * @param {String} method - The signature of the atomic function to construct.
  24350. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24351. * @param {Node} valueNode - The value that mutates the atomic variable.
  24352. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24353. * @returns {AtomicFunctionNode}
  24354. */
  24355. const atomicNode = nodeProxy( AtomicFunctionNode );
  24356. /**
  24357. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  24358. *
  24359. * @function
  24360. * @param {String} method - The signature of the atomic function to construct.
  24361. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24362. * @param {Node} valueNode - The value that mutates the atomic variable.
  24363. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24364. * @returns {AtomicFunctionNode}
  24365. */
  24366. const atomicFunc = ( method, pointerNode, valueNode, storeNode = null ) => {
  24367. const node = atomicNode( method, pointerNode, valueNode, storeNode );
  24368. node.append();
  24369. return node;
  24370. };
  24371. /**
  24372. * Stores a value in the atomic variable.
  24373. *
  24374. * @function
  24375. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24376. * @param {Node} valueNode - The value that mutates the atomic variable.
  24377. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24378. * @returns {AtomicFunctionNode}
  24379. */
  24380. const atomicStore = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode, storeNode );
  24381. /**
  24382. * Increments the value stored in the atomic variable.
  24383. *
  24384. * @function
  24385. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24386. * @param {Node} valueNode - The value that mutates the atomic variable.
  24387. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24388. * @returns {AtomicFunctionNode}
  24389. */
  24390. const atomicAdd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode, storeNode );
  24391. /**
  24392. * Decrements the value stored in the atomic variable.
  24393. *
  24394. * @function
  24395. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24396. * @param {Node} valueNode - The value that mutates the atomic variable.
  24397. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24398. * @returns {AtomicFunctionNode}
  24399. */
  24400. const atomicSub = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode, storeNode );
  24401. /**
  24402. * Stores in an atomic variable the maximum between its current value and a parameter.
  24403. *
  24404. * @function
  24405. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24406. * @param {Node} valueNode - The value that mutates the atomic variable.
  24407. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24408. * @returns {AtomicFunctionNode}
  24409. */
  24410. const atomicMax = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode, storeNode );
  24411. /**
  24412. * Stores in an atomic variable the minimum between its current value and a parameter.
  24413. *
  24414. * @function
  24415. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24416. * @param {Node} valueNode - The value that mutates the atomic variable.
  24417. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24418. * @returns {AtomicFunctionNode}
  24419. */
  24420. const atomicMin = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode, storeNode );
  24421. /**
  24422. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  24423. *
  24424. * @function
  24425. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24426. * @param {Node} valueNode - The value that mutates the atomic variable.
  24427. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24428. * @returns {AtomicFunctionNode}
  24429. */
  24430. const atomicAnd = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode, storeNode );
  24431. /**
  24432. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  24433. *
  24434. * @function
  24435. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24436. * @param {Node} valueNode - The value that mutates the atomic variable.
  24437. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24438. * @returns {AtomicFunctionNode}
  24439. */
  24440. const atomicOr = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode, storeNode );
  24441. /**
  24442. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  24443. *
  24444. * @function
  24445. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  24446. * @param {Node} valueNode - The value that mutates the atomic variable.
  24447. * @param {Node?} [storeNode=null] - A variable storing the return value of an atomic operation, typically the value of the atomic variable before the operation.
  24448. * @returns {AtomicFunctionNode}
  24449. */
  24450. const atomicXor = ( pointerNode, valueNode, storeNode = null ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode, storeNode );
  24451. /** @module Lights **/
  24452. let uniformsLib;
  24453. function getLightData( light ) {
  24454. uniformsLib = uniformsLib || new WeakMap();
  24455. let uniforms = uniformsLib.get( light );
  24456. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  24457. return uniforms;
  24458. }
  24459. /**
  24460. * TSL function for getting a shadow matrix uniform node for the given light.
  24461. *
  24462. * @function
  24463. * @param {Light} light -The light source.
  24464. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  24465. */
  24466. function lightShadowMatrix( light ) {
  24467. const data = getLightData( light );
  24468. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24469. if ( light.castShadow !== true ) {
  24470. light.shadow.updateMatrices( light );
  24471. }
  24472. return light.shadow.matrix;
  24473. } ) );
  24474. }
  24475. /**
  24476. * TSL function for getting projected uv coordinates for the given light.
  24477. * Relevant when using maps with spot lights.
  24478. *
  24479. * @function
  24480. * @param {Light} light -The light source.
  24481. * @returns {Node<vec3>} The projected uvs.
  24482. */
  24483. function lightProjectionUV( light ) {
  24484. const data = getLightData( light );
  24485. if ( data.projectionUV === undefined ) {
  24486. const spotLightCoord = lightShadowMatrix( light ).mul( positionWorld );
  24487. data.projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  24488. }
  24489. return data.projectionUV;
  24490. }
  24491. /**
  24492. * TSL function for getting the position in world space for the given light.
  24493. *
  24494. * @function
  24495. * @param {Light} light -The light source.
  24496. * @returns {UniformNode<vec3>} The light's position in world space.
  24497. */
  24498. function lightPosition( light ) {
  24499. const data = getLightData( light );
  24500. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  24501. }
  24502. /**
  24503. * TSL function for getting the light target position in world space for the given light.
  24504. *
  24505. * @function
  24506. * @param {Light} light -The light source.
  24507. * @returns {UniformNode<vec3>} The light target position in world space.
  24508. */
  24509. function lightTargetPosition( light ) {
  24510. const data = getLightData( light );
  24511. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  24512. }
  24513. /**
  24514. * TSL function for getting the position in view space for the given light.
  24515. *
  24516. * @function
  24517. * @param {Light} light -The light source.
  24518. * @returns {UniformNode<vec3>} The light's position in view space.
  24519. */
  24520. function lightViewPosition( light ) {
  24521. const data = getLightData( light );
  24522. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  24523. self.value = self.value || new Vector3();
  24524. self.value.setFromMatrixPosition( light.matrixWorld );
  24525. self.value.applyMatrix4( camera.matrixWorldInverse );
  24526. } ) );
  24527. }
  24528. /**
  24529. * TSL function for getting the light target direction for the given light.
  24530. *
  24531. * @function
  24532. * @param {Light} light -The light source.
  24533. * @returns {Node<vec3>} The light's target direction.
  24534. */
  24535. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  24536. /** @module LightsNode **/
  24537. const sortLights = ( lights ) => {
  24538. return lights.sort( ( a, b ) => a.id - b.id );
  24539. };
  24540. const getLightNodeById = ( id, lightNodes ) => {
  24541. for ( const lightNode of lightNodes ) {
  24542. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  24543. return lightNode;
  24544. }
  24545. }
  24546. return null;
  24547. };
  24548. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  24549. /**
  24550. * This node represents the scene's lighting and manages the lighting model's life cycle
  24551. * for the current build 3D object. It is responsible for computing the total outgoing
  24552. * light in a given lighting context.
  24553. *
  24554. * @augments Node
  24555. */
  24556. class LightsNode extends Node {
  24557. static get type() {
  24558. return 'LightsNode';
  24559. }
  24560. /**
  24561. * Constructs a new lights node.
  24562. */
  24563. constructor() {
  24564. super( 'vec3' );
  24565. /**
  24566. * A node representing the total diffuse light.
  24567. *
  24568. * @type {Node<vec3>}
  24569. */
  24570. this.totalDiffuseNode = vec3().toVar( 'totalDiffuse' );
  24571. /**
  24572. * A node representing the total specular light.
  24573. *
  24574. * @type {Node<vec3>}
  24575. */
  24576. this.totalSpecularNode = vec3().toVar( 'totalSpecular' );
  24577. /**
  24578. * A node representing the outgoing light.
  24579. *
  24580. * @type {Node<vec3>}
  24581. */
  24582. this.outgoingLightNode = vec3().toVar( 'outgoingLight' );
  24583. /**
  24584. * An array representing the lights in the scene.
  24585. *
  24586. * @private
  24587. * @type {Array<Light>}
  24588. */
  24589. this._lights = [];
  24590. /**
  24591. * For each light in the scene, this node will create a
  24592. * corresponding light node.
  24593. *
  24594. * @private
  24595. * @type {Array<LightingNode>?}
  24596. * @default null
  24597. */
  24598. this._lightNodes = null;
  24599. /**
  24600. * A hash for identifying the current light nodes setup.
  24601. *
  24602. * @private
  24603. * @type {String?}
  24604. * @default null
  24605. */
  24606. this._lightNodesHash = null;
  24607. /**
  24608. * `LightsNode` sets this property to `true` by default.
  24609. *
  24610. * @type {Boolean}
  24611. * @default true
  24612. */
  24613. this.global = true;
  24614. }
  24615. /**
  24616. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  24617. * light IDs into the cache key.
  24618. *
  24619. * @return {Number} The custom cache key.
  24620. */
  24621. customCacheKey() {
  24622. const lightIDs = [];
  24623. const lights = this._lights;
  24624. for ( let i = 0; i < lights.length; i ++ ) {
  24625. lightIDs.push( lights[ i ].id );
  24626. }
  24627. return hashArray( lightIDs );
  24628. }
  24629. /**
  24630. * Computes a hash value for identifying the current light nodes setup.
  24631. *
  24632. * @param {NodeBuilder} builder - A reference to the current node builder.
  24633. * @return {String} The computed hash.
  24634. */
  24635. getHash( builder ) {
  24636. if ( this._lightNodesHash === null ) {
  24637. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24638. const hash = [];
  24639. for ( const lightNode of this._lightNodes ) {
  24640. hash.push( lightNode.getSelf().getHash() );
  24641. }
  24642. this._lightNodesHash = 'lights-' + hash.join( ',' );
  24643. }
  24644. return this._lightNodesHash;
  24645. }
  24646. analyze( builder ) {
  24647. const properties = builder.getDataFromNode( this );
  24648. for ( const node of properties.nodes ) {
  24649. node.build( builder );
  24650. }
  24651. }
  24652. /**
  24653. * Creates lighting nodes for each scene light. This makes it possible to further
  24654. * process lights in the node system.
  24655. *
  24656. * @param {NodeBuilder} builder - A reference to the current node builder.
  24657. */
  24658. setupLightsNode( builder ) {
  24659. const lightNodes = [];
  24660. const previousLightNodes = this._lightNodes;
  24661. const lights = sortLights( this._lights );
  24662. const nodeLibrary = builder.renderer.library;
  24663. for ( const light of lights ) {
  24664. if ( light.isNode ) {
  24665. lightNodes.push( nodeObject( light ) );
  24666. } else {
  24667. let lightNode = null;
  24668. if ( previousLightNodes !== null ) {
  24669. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  24670. }
  24671. if ( lightNode === null ) {
  24672. // find the corresponding node type for a given light
  24673. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  24674. if ( lightNodeClass === null ) {
  24675. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  24676. continue;
  24677. }
  24678. let lightNode = null;
  24679. if ( ! _lightsNodeRef.has( light ) ) {
  24680. lightNode = nodeObject( new lightNodeClass( light ) );
  24681. _lightsNodeRef.set( light, lightNode );
  24682. } else {
  24683. lightNode = _lightsNodeRef.get( light );
  24684. }
  24685. lightNodes.push( lightNode );
  24686. }
  24687. }
  24688. }
  24689. this._lightNodes = lightNodes;
  24690. }
  24691. /**
  24692. * Setups the internal lights by building all respective
  24693. * light nodes.
  24694. *
  24695. * @param {NodeBuilder} builder - A reference to the current node builder.
  24696. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  24697. */
  24698. setupLights( builder, lightNodes ) {
  24699. for ( const lightNode of lightNodes ) {
  24700. lightNode.build( builder );
  24701. }
  24702. }
  24703. /**
  24704. * The implementation makes sure that for each light in the scene
  24705. * there is a corresponding light node. By building the light nodes
  24706. * and evaluating the lighting model the outgoing light is computed.
  24707. *
  24708. * @param {NodeBuilder} builder - A reference to the current node builder.
  24709. * @return {Node<vec3>} A node representing the outgoing light.
  24710. */
  24711. setup( builder ) {
  24712. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  24713. const context = builder.context;
  24714. const lightingModel = context.lightingModel;
  24715. let outgoingLightNode = this.outgoingLightNode;
  24716. if ( lightingModel ) {
  24717. const { _lightNodes, totalDiffuseNode, totalSpecularNode } = this;
  24718. context.outgoingLight = outgoingLightNode;
  24719. const stack = builder.addStack();
  24720. //
  24721. const properties = builder.getDataFromNode( this );
  24722. properties.nodes = stack.nodes;
  24723. //
  24724. lightingModel.start( context, stack, builder );
  24725. // lights
  24726. this.setupLights( builder, _lightNodes );
  24727. //
  24728. lightingModel.indirect( context, stack, builder );
  24729. //
  24730. const { backdrop, backdropAlpha } = context;
  24731. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  24732. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  24733. if ( backdrop !== null ) {
  24734. if ( backdropAlpha !== null ) {
  24735. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  24736. } else {
  24737. totalDiffuse = vec3( backdrop );
  24738. }
  24739. context.material.transparent = true;
  24740. }
  24741. totalDiffuseNode.assign( totalDiffuse );
  24742. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  24743. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  24744. //
  24745. lightingModel.finish( context, stack, builder );
  24746. //
  24747. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  24748. }
  24749. return outgoingLightNode;
  24750. }
  24751. /**
  24752. * Configures this node with an array of lights.
  24753. *
  24754. * @param {Array<Light>} lights - An array of lights.
  24755. * @return {LightsNode} A reference to this node.
  24756. */
  24757. setLights( lights ) {
  24758. this._lights = lights;
  24759. this._lightNodes = null;
  24760. this._lightNodesHash = null;
  24761. return this;
  24762. }
  24763. /**
  24764. * Returns an array of the scene's lights.
  24765. *
  24766. * @return {Array<Light>} The scene's lights.
  24767. */
  24768. getLights() {
  24769. return this._lights;
  24770. }
  24771. /**
  24772. * Whether the scene has lights or not.
  24773. *
  24774. * @type {Boolean}
  24775. */
  24776. get hasLights() {
  24777. return this._lights.length > 0;
  24778. }
  24779. }
  24780. /**
  24781. * TSL function for creating an instance of `LightsNode` and configuring
  24782. * it with the given array of lights.
  24783. *
  24784. * @function
  24785. * @param {Array<Light>} lights - An array of lights.
  24786. * @return {LightsNode} The created lights node.
  24787. */
  24788. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  24789. /** @module ShadowBaseNode **/
  24790. /**
  24791. * Base class for all shadow nodes.
  24792. *
  24793. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  24794. * Lighting nodes might share the same shadow node type or use specific ones depending on
  24795. * their requirements.
  24796. *
  24797. * @augments Node
  24798. */
  24799. class ShadowBaseNode extends Node {
  24800. static get type() {
  24801. return 'ShadowBaseNode';
  24802. }
  24803. /**
  24804. * Constructs a new shadow base node.
  24805. *
  24806. * @param {Light} light - The shadow casting light.
  24807. */
  24808. constructor( light ) {
  24809. super();
  24810. /**
  24811. * The shadow casting light.
  24812. *
  24813. * @type {Light}
  24814. */
  24815. this.light = light;
  24816. /**
  24817. * Overwritten since shadows are updated by default per render.
  24818. *
  24819. * @type {String}
  24820. * @default 'render'
  24821. */
  24822. this.updateBeforeType = NodeUpdateType.RENDER;
  24823. /**
  24824. * This flag can be used for type testing.
  24825. *
  24826. * @type {Boolean}
  24827. * @readonly
  24828. * @default true
  24829. */
  24830. this.isShadowBaseNode = true;
  24831. }
  24832. /**
  24833. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  24834. *
  24835. * @param {(NodeBuilder|{Material})} object - A configuration object that must at least hold a material reference.
  24836. */
  24837. setupShadowPosition( { material } ) {
  24838. // Use assign inside an Fn()
  24839. shadowPositionWorld.assign( material.shadowPositionNode || positionWorld );
  24840. }
  24841. /**
  24842. * Can be called when the shadow isn't required anymore. That can happen when
  24843. * a lighting node stops casting shadows by setting {@link Object3D#castShadow}
  24844. * to `false`.
  24845. */
  24846. dispose() {
  24847. this.updateBeforeType = NodeUpdateType.NONE;
  24848. }
  24849. }
  24850. /**
  24851. * TSL object that represents the vertex position in world space during the shadow pass.
  24852. *
  24853. * @type {Node<vec3>}
  24854. */
  24855. const shadowPositionWorld = /*@__PURE__*/ vec3().toVar( 'shadowPositionWorld' );
  24856. /** @module RendererUtils **/
  24857. /**
  24858. * Saves the state of the given renderer and stores it into the given state object.
  24859. *
  24860. * If not state object is provided, the function creates one.
  24861. *
  24862. * @function
  24863. * @param {Renderer} renderer - The renderer.
  24864. * @param {Object} [state={}] - The state.
  24865. * @return {Object} The state.
  24866. */
  24867. function saveRendererState( renderer, state = {} ) {
  24868. state.toneMapping = renderer.toneMapping;
  24869. state.toneMappingExposure = renderer.toneMappingExposure;
  24870. state.outputColorSpace = renderer.outputColorSpace;
  24871. state.renderTarget = renderer.getRenderTarget();
  24872. state.activeCubeFace = renderer.getActiveCubeFace();
  24873. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  24874. state.renderObjectFunction = renderer.getRenderObjectFunction();
  24875. state.pixelRatio = renderer.getPixelRatio();
  24876. state.mrt = renderer.getMRT();
  24877. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  24878. state.clearAlpha = renderer.getClearAlpha();
  24879. state.autoClear = renderer.autoClear;
  24880. state.scissorTest = renderer.getScissorTest();
  24881. return state;
  24882. }
  24883. /**
  24884. * Saves the state of the given renderer and stores it into the given state object.
  24885. * Besides, the function also resets the state of the renderer to its default values.
  24886. *
  24887. * If not state object is provided, the function creates one.
  24888. *
  24889. * @function
  24890. * @param {Renderer} renderer - The renderer.
  24891. * @param {Object} [state={}] - The state.
  24892. * @return {Object} The state.
  24893. */
  24894. function resetRendererState( renderer, state ) {
  24895. state = saveRendererState( renderer, state );
  24896. renderer.setMRT( null );
  24897. renderer.setRenderObjectFunction( null );
  24898. renderer.setClearColor( 0x000000, 1 );
  24899. renderer.autoClear = true;
  24900. return state;
  24901. }
  24902. /**
  24903. * Restores the state of the given renderer from the given state object.
  24904. *
  24905. * @function
  24906. * @param {Renderer} renderer - The renderer.
  24907. * @param {Object} state - The state to restore.
  24908. */
  24909. function restoreRendererState( renderer, state ) {
  24910. renderer.toneMapping = state.toneMapping;
  24911. renderer.toneMappingExposure = state.toneMappingExposure;
  24912. renderer.outputColorSpace = state.outputColorSpace;
  24913. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  24914. renderer.setRenderObjectFunction( state.renderObjectFunction );
  24915. renderer.setPixelRatio( state.pixelRatio );
  24916. renderer.setMRT( state.mrt );
  24917. renderer.setClearColor( state.clearColor, state.clearAlpha );
  24918. renderer.autoClear = state.autoClear;
  24919. renderer.setScissorTest( state.scissorTest );
  24920. }
  24921. /**
  24922. * Saves the state of the given scene and stores it into the given state object.
  24923. *
  24924. * If not state object is provided, the function creates one.
  24925. *
  24926. * @function
  24927. * @param {Scene} scene - The scene.
  24928. * @param {Object} [state={}] - The state.
  24929. * @return {Object} The state.
  24930. */
  24931. function saveSceneState( scene, state = {} ) {
  24932. state.background = scene.background;
  24933. state.backgroundNode = scene.backgroundNode;
  24934. state.overrideMaterial = scene.overrideMaterial;
  24935. return state;
  24936. }
  24937. /**
  24938. * Saves the state of the given scene and stores it into the given state object.
  24939. * Besides, the function also resets the state of the scene to its default values.
  24940. *
  24941. * If not state object is provided, the function creates one.
  24942. *
  24943. * @function
  24944. * @param {Scene} scene - The scene.
  24945. * @param {Object} [state={}] - The state.
  24946. * @return {Object} The state.
  24947. */
  24948. function resetSceneState( scene, state ) {
  24949. state = saveSceneState( scene, state );
  24950. scene.background = null;
  24951. scene.backgroundNode = null;
  24952. scene.overrideMaterial = null;
  24953. return state;
  24954. }
  24955. /**
  24956. * Restores the state of the given scene from the given state object.
  24957. *
  24958. * @function
  24959. * @param {Scene} scene - The scene.
  24960. * @param {Object} state - The state to restore.
  24961. */
  24962. function restoreSceneState( scene, state ) {
  24963. scene.background = state.background;
  24964. scene.backgroundNode = state.backgroundNode;
  24965. scene.overrideMaterial = state.overrideMaterial;
  24966. }
  24967. /**
  24968. * Saves the state of the given renderer and scene and stores it into the given state object.
  24969. *
  24970. * If not state object is provided, the function creates one.
  24971. *
  24972. * @function
  24973. * @param {Renderer} renderer - The renderer.
  24974. * @param {Scene} scene - The scene.
  24975. * @param {Object} [state={}] - The state.
  24976. * @return {Object} The state.
  24977. */
  24978. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  24979. state = saveRendererState( renderer, state );
  24980. state = saveSceneState( scene, state );
  24981. return state;
  24982. }
  24983. /**
  24984. * Saves the state of the given renderer and scene and stores it into the given state object.
  24985. * Besides, the function also resets the state of the renderer and scene to its default values.
  24986. *
  24987. * If not state object is provided, the function creates one.
  24988. *
  24989. * @function
  24990. * @param {Renderer} renderer - The renderer.
  24991. * @param {Scene} scene - The scene.
  24992. * @param {Object} [state={}] - The state.
  24993. * @return {Object} The state.
  24994. */
  24995. function resetRendererAndSceneState( renderer, scene, state ) {
  24996. state = resetRendererState( renderer, state );
  24997. state = resetSceneState( scene, state );
  24998. return state;
  24999. }
  25000. /**
  25001. * Restores the state of the given renderer and scene from the given state object.
  25002. *
  25003. * @function
  25004. * @param {Renderer} renderer - The renderer.
  25005. * @param {Scene} scene - The scene.
  25006. * @param {Object} state - The state to restore.
  25007. */
  25008. function restoreRendererAndSceneState( renderer, scene, state ) {
  25009. restoreRendererState( renderer, state );
  25010. restoreSceneState( scene, state );
  25011. }
  25012. var RendererUtils = /*#__PURE__*/Object.freeze({
  25013. __proto__: null,
  25014. resetRendererAndSceneState: resetRendererAndSceneState,
  25015. resetRendererState: resetRendererState,
  25016. resetSceneState: resetSceneState,
  25017. restoreRendererAndSceneState: restoreRendererAndSceneState,
  25018. restoreRendererState: restoreRendererState,
  25019. restoreSceneState: restoreSceneState,
  25020. saveRendererAndSceneState: saveRendererAndSceneState,
  25021. saveRendererState: saveRendererState,
  25022. saveSceneState: saveSceneState
  25023. });
  25024. /** @module ShadowNode **/
  25025. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  25026. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  25027. let dist = positionWorld.sub( position ).length();
  25028. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  25029. dist = dist.saturate(); // clamp to [ 0, 1 ]
  25030. return dist;
  25031. } );
  25032. const linearShadowDistance = ( light ) => {
  25033. const camera = light.shadow.camera;
  25034. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  25035. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  25036. const referencePosition = objectPosition( light );
  25037. return linearDistance( referencePosition, nearDistance, farDistance );
  25038. };
  25039. const getShadowMaterial = ( light ) => {
  25040. let material = shadowMaterialLib.get( light );
  25041. if ( material === undefined ) {
  25042. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  25043. material = new NodeMaterial();
  25044. material.colorNode = vec4( 0, 0, 0, 1 );
  25045. material.depthNode = depthNode;
  25046. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  25047. material.name = 'ShadowMaterial';
  25048. material.fog = false;
  25049. shadowMaterialLib.set( light, material );
  25050. }
  25051. return material;
  25052. };
  25053. /**
  25054. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  25055. * with a binary `[0,1]` result.
  25056. *
  25057. * @method
  25058. * @param {Object} inputs - The input parameter object.
  25059. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25060. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25061. * @return {Node<float>} The filtering result.
  25062. */
  25063. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25064. return texture( depthTexture, shadowCoord.xy ).compare( shadowCoord.z );
  25065. } );
  25066. /**
  25067. * A shadow filtering function performing PCF filtering.
  25068. *
  25069. * @method
  25070. * @param {Object} inputs - The input parameter object.
  25071. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25072. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25073. * @param {LightShadow} inputs.shadow - The light shadow.
  25074. * @return {Node<float>} The filtering result.
  25075. */
  25076. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25077. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25078. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25079. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25080. const texelSize = vec2( 1 ).div( mapSize );
  25081. const dx0 = texelSize.x.negate().mul( radius );
  25082. const dy0 = texelSize.y.negate().mul( radius );
  25083. const dx1 = texelSize.x.mul( radius );
  25084. const dy1 = texelSize.y.mul( radius );
  25085. const dx2 = dx0.div( 2 );
  25086. const dy2 = dy0.div( 2 );
  25087. const dx3 = dx1.div( 2 );
  25088. const dy3 = dy1.div( 2 );
  25089. return add(
  25090. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  25091. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  25092. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  25093. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  25094. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  25095. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  25096. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  25097. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  25098. depthCompare( shadowCoord.xy, shadowCoord.z ),
  25099. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  25100. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  25101. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  25102. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  25103. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  25104. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  25105. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  25106. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  25107. ).mul( 1 / 17 );
  25108. } );
  25109. /**
  25110. * A shadow filtering function performing PCF soft filtering.
  25111. *
  25112. * @method
  25113. * @param {Object} inputs - The input parameter object.
  25114. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25115. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25116. * @param {LightShadow} inputs.shadow - The light shadow.
  25117. * @return {Node<float>} The filtering result.
  25118. */
  25119. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow } ) => {
  25120. const depthCompare = ( uv, compare ) => texture( depthTexture, uv ).compare( compare );
  25121. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25122. const texelSize = vec2( 1 ).div( mapSize );
  25123. const dx = texelSize.x;
  25124. const dy = texelSize.y;
  25125. const uv = shadowCoord.xy;
  25126. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  25127. uv.subAssign( f.mul( texelSize ) );
  25128. return add(
  25129. depthCompare( uv, shadowCoord.z ),
  25130. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  25131. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  25132. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  25133. mix(
  25134. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  25135. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  25136. f.x
  25137. ),
  25138. mix(
  25139. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  25140. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  25141. f.x
  25142. ),
  25143. mix(
  25144. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  25145. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  25146. f.y
  25147. ),
  25148. mix(
  25149. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  25150. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  25151. f.y
  25152. ),
  25153. mix(
  25154. mix(
  25155. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  25156. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  25157. f.x
  25158. ),
  25159. mix(
  25160. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  25161. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  25162. f.x
  25163. ),
  25164. f.y
  25165. )
  25166. ).mul( 1 / 9 );
  25167. } );
  25168. /**
  25169. * A shadow filtering function performing VSM filtering.
  25170. *
  25171. * @method
  25172. * @param {Object} inputs - The input parameter object.
  25173. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25174. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  25175. * @return {Node<float>} The filtering result.
  25176. */
  25177. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord } ) => {
  25178. const occlusion = float( 1 ).toVar();
  25179. const distribution = texture( depthTexture ).sample( shadowCoord.xy ).rg;
  25180. const hardShadow = step( shadowCoord.z, distribution.x );
  25181. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  25182. const distance = shadowCoord.z.sub( distribution.x );
  25183. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  25184. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  25185. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  25186. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  25187. } );
  25188. return occlusion;
  25189. } );
  25190. /**
  25191. * Represents the shader code for the first VSM render pass.
  25192. *
  25193. * @method
  25194. * @param {Object} inputs - The input parameter object.
  25195. * @param {Node<float>} inputs.samples - The number of samples
  25196. * @param {Node<float>} inputs.radius - The radius.
  25197. * @param {Node<float>} inputs.size - The size.
  25198. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  25199. * @return {Node<vec2>} The VSM output.
  25200. */
  25201. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25202. const mean = float( 0 ).toVar();
  25203. const squaredMean = float( 0 ).toVar();
  25204. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25205. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  25206. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25207. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25208. const depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) ).x;
  25209. mean.addAssign( depth );
  25210. squaredMean.addAssign( depth.mul( depth ) );
  25211. } );
  25212. mean.divAssign( samples );
  25213. squaredMean.divAssign( samples );
  25214. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25215. return vec2( mean, std_dev );
  25216. } );
  25217. /**
  25218. * Represents the shader code for the second VSM render pass.
  25219. *
  25220. * @method
  25221. * @param {Object} inputs - The input parameter object.
  25222. * @param {Node<float>} inputs.samples - The number of samples
  25223. * @param {Node<float>} inputs.radius - The radius.
  25224. * @param {Node<float>} inputs.size - The size.
  25225. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  25226. * @return {Node<vec2>} The VSM output.
  25227. */
  25228. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass } ) => {
  25229. const mean = float( 0 ).toVar();
  25230. const squaredMean = float( 0 ).toVar();
  25231. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  25232. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( - 1 ) );
  25233. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  25234. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  25235. const distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  25236. mean.addAssign( distribution.x );
  25237. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  25238. } );
  25239. mean.divAssign( samples );
  25240. squaredMean.divAssign( samples );
  25241. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  25242. return vec2( mean, std_dev );
  25243. } );
  25244. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  25245. //
  25246. let _rendererState;
  25247. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  25248. /**
  25249. * Represents the default shadow implementation for lighting nodes.
  25250. *
  25251. * @augments module:ShadowBaseNode~ShadowBaseNode
  25252. */
  25253. class ShadowNode extends ShadowBaseNode {
  25254. static get type() {
  25255. return 'ShadowNode';
  25256. }
  25257. /**
  25258. * Constructs a new shadow node.
  25259. *
  25260. * @param {Light} light - The shadow casting light.
  25261. * @param {LightShadow?} [shadow=null] - An optional light shadow.
  25262. */
  25263. constructor( light, shadow = null ) {
  25264. super( light );
  25265. /**
  25266. * The light shadow which defines the properties light's
  25267. * shadow.
  25268. *
  25269. * @type {LightShadow?}
  25270. * @default null
  25271. */
  25272. this.shadow = shadow || light.shadow;
  25273. /**
  25274. * A reference to the shadow map which is a render target.
  25275. *
  25276. * @type {RenderTarget?}
  25277. * @default null
  25278. */
  25279. this.shadowMap = null;
  25280. /**
  25281. * Only relevant for VSM shadows. Render target for the
  25282. * first VSM render pass.
  25283. *
  25284. * @type {RenderTarget?}
  25285. * @default null
  25286. */
  25287. this.vsmShadowMapVertical = null;
  25288. /**
  25289. * Only relevant for VSM shadows. Render target for the
  25290. * second VSM render pass.
  25291. *
  25292. * @type {RenderTarget?}
  25293. * @default null
  25294. */
  25295. this.vsmShadowMapHorizontal = null;
  25296. /**
  25297. * Only relevant for VSM shadows. Node material which
  25298. * is used to render the first VSM pass.
  25299. *
  25300. * @type {NodeMaterial?}
  25301. * @default null
  25302. */
  25303. this.vsmMaterialVertical = null;
  25304. /**
  25305. * Only relevant for VSM shadows. Node material which
  25306. * is used to render the second VSM pass.
  25307. *
  25308. * @type {NodeMaterial?}
  25309. * @default null
  25310. */
  25311. this.vsmMaterialHorizontal = null;
  25312. /**
  25313. * A reference to the output node which defines the
  25314. * final result of this shadow node.
  25315. *
  25316. * @type {Node?}
  25317. * @private
  25318. * @default null
  25319. */
  25320. this._node = null;
  25321. /**
  25322. * This flag can be used for type testing.
  25323. *
  25324. * @type {Boolean}
  25325. * @readonly
  25326. * @default true
  25327. */
  25328. this.isShadowNode = true;
  25329. }
  25330. /**
  25331. * Setups the shadow filtering.
  25332. *
  25333. * @param {NodeBuilder} builder - A reference to the current node builder.
  25334. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25335. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25336. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25337. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25338. * @param {LightShadow} inputs.shadow - The light shadow.
  25339. * @return {Node<float>} The result node of the shadow filtering.
  25340. */
  25341. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow } ) {
  25342. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  25343. .and( shadowCoord.x.lessThanEqual( 1 ) )
  25344. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  25345. .and( shadowCoord.y.lessThanEqual( 1 ) )
  25346. .and( shadowCoord.z.lessThanEqual( 1 ) );
  25347. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow } );
  25348. return frustumTest.select( shadowNode, float( 1 ) );
  25349. }
  25350. /**
  25351. * Setups the shadow coordinates.
  25352. *
  25353. * @param {NodeBuilder} builder - A reference to the current node builder.
  25354. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25355. * @return {Node<vec3>} The shadow coordinates.
  25356. */
  25357. setupShadowCoord( builder, shadowPosition ) {
  25358. const { shadow } = this;
  25359. const { renderer } = builder;
  25360. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25361. let shadowCoord = shadowPosition;
  25362. let coordZ;
  25363. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  25364. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  25365. coordZ = shadowCoord.z;
  25366. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  25367. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  25368. }
  25369. } else {
  25370. const w = shadowCoord.w;
  25371. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  25372. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  25373. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  25374. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  25375. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  25376. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  25377. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  25378. }
  25379. shadowCoord = vec3(
  25380. shadowCoord.x,
  25381. shadowCoord.y.oneMinus(), // follow webgpu standards
  25382. coordZ.add( bias )
  25383. );
  25384. return shadowCoord;
  25385. }
  25386. /**
  25387. * Returns the shadow filtering function for the given shadow type.
  25388. *
  25389. * @param {Number} type - The shadow type.
  25390. * @return {Function} The filtering function.
  25391. */
  25392. getShadowFilterFn( type ) {
  25393. return _shadowFilterLib[ type ];
  25394. }
  25395. /**
  25396. * Setups the shadow output node.
  25397. *
  25398. * @param {NodeBuilder} builder - A reference to the current node builder.
  25399. * @return {Node<vec3>} The shadow output node.
  25400. */
  25401. setupShadow( builder ) {
  25402. const { renderer } = builder;
  25403. const { light, shadow } = this;
  25404. const shadowMapType = renderer.shadowMap.type;
  25405. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  25406. depthTexture.compareFunction = LessCompare;
  25407. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  25408. shadowMap.depthTexture = depthTexture;
  25409. shadow.camera.updateProjectionMatrix();
  25410. // VSM
  25411. if ( shadowMapType === VSMShadowMap ) {
  25412. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  25413. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25414. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType } );
  25415. const shadowPassVertical = texture( depthTexture );
  25416. const shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  25417. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  25418. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25419. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  25420. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  25421. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical } ).context( builder.getSharedContext() );
  25422. material.name = 'VSMVertical';
  25423. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  25424. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal } ).context( builder.getSharedContext() );
  25425. material.name = 'VSMHorizontal';
  25426. }
  25427. //
  25428. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  25429. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  25430. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  25431. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  25432. //
  25433. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  25434. if ( filterFn === null ) {
  25435. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  25436. }
  25437. const shadowDepthTexture = ( shadowMapType === VSMShadowMap ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  25438. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow } );
  25439. const shadowColor = texture( shadowMap.texture, shadowCoord );
  25440. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  25441. this.shadowMap = shadowMap;
  25442. this.shadow.map = shadowMap;
  25443. return shadowOutput;
  25444. }
  25445. /**
  25446. * The implementation performs the setup of the output node. An output is only
  25447. * produces if shadow mapping is globally enabled in the renderer.
  25448. *
  25449. * @param {NodeBuilder} builder - A reference to the current node builder.
  25450. * @return {ShaderCallNodeInternal} The output node.
  25451. */
  25452. setup( builder ) {
  25453. if ( builder.renderer.shadowMap.enabled === false ) return;
  25454. return Fn( () => {
  25455. let node = this._node;
  25456. this.setupShadowPosition( builder );
  25457. if ( node === null ) {
  25458. this._node = node = this.setupShadow( builder );
  25459. }
  25460. if ( builder.material.shadowNode ) { // @deprecated, r171
  25461. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  25462. }
  25463. if ( builder.material.receivedShadowNode ) {
  25464. node = builder.material.receivedShadowNode( node );
  25465. }
  25466. return node;
  25467. } )();
  25468. }
  25469. /**
  25470. * Renders the shadow. The logic of this function could be included
  25471. * into {@link ShadowNode#updateShadow} however more specialized shadow
  25472. * nodes might require a custom shadow map rendering. By having a
  25473. * dedicated method, it's easier to overwrite the default behavior.
  25474. *
  25475. * @param {NodeFrame} frame - A reference to the current node frame.
  25476. */
  25477. renderShadow( frame ) {
  25478. const { shadow, shadowMap, light } = this;
  25479. const { renderer, scene } = frame;
  25480. shadow.updateMatrices( light );
  25481. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25482. renderer.render( scene, shadow.camera );
  25483. }
  25484. /**
  25485. * Updates the shadow.
  25486. *
  25487. * @param {NodeFrame} frame - A reference to the current node frame.
  25488. */
  25489. updateShadow( frame ) {
  25490. const { shadowMap, light, shadow } = this;
  25491. const { renderer, scene, camera } = frame;
  25492. const shadowType = renderer.shadowMap.type;
  25493. const depthVersion = shadowMap.depthTexture.version;
  25494. this._depthVersionCached = depthVersion;
  25495. shadow.camera.layers.mask = camera.layers.mask;
  25496. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25497. const currentMRT = renderer.getMRT();
  25498. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  25499. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  25500. scene.overrideMaterial = getShadowMaterial( light );
  25501. renderer.setRenderObjectFunction( ( object, scene, _camera, geometry, material, group, ...params ) => {
  25502. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  25503. if ( useVelocity ) {
  25504. getDataFromObject( object ).useVelocity = true;
  25505. }
  25506. object.onBeforeShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25507. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  25508. object.onAfterShadow( renderer, object, camera, shadow.camera, geometry, scene.overrideMaterial, group );
  25509. }
  25510. } );
  25511. renderer.setRenderTarget( shadowMap );
  25512. this.renderShadow( frame );
  25513. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25514. // vsm blur pass
  25515. if ( light.isPointLight !== true && shadowType === VSMShadowMap ) {
  25516. this.vsmPass( renderer );
  25517. }
  25518. restoreRendererAndSceneState( renderer, scene, _rendererState );
  25519. }
  25520. /**
  25521. * For VSM additional render passes are required.
  25522. *
  25523. * @param {Renderer} renderer - A reference to the current renderer.
  25524. */
  25525. vsmPass( renderer ) {
  25526. const { shadow } = this;
  25527. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25528. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height );
  25529. renderer.setRenderTarget( this.vsmShadowMapVertical );
  25530. _quadMesh.material = this.vsmMaterialVertical;
  25531. _quadMesh.render( renderer );
  25532. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  25533. _quadMesh.material = this.vsmMaterialHorizontal;
  25534. _quadMesh.render( renderer );
  25535. }
  25536. /**
  25537. * Frees the internal resources of this shadow node.
  25538. */
  25539. dispose() {
  25540. this.shadowMap.dispose();
  25541. this.shadowMap = null;
  25542. if ( this.vsmShadowMapVertical !== null ) {
  25543. this.vsmShadowMapVertical.dispose();
  25544. this.vsmShadowMapVertical = null;
  25545. this.vsmMaterialVertical.dispose();
  25546. this.vsmMaterialVertical = null;
  25547. }
  25548. if ( this.vsmShadowMapHorizontal !== null ) {
  25549. this.vsmShadowMapHorizontal.dispose();
  25550. this.vsmShadowMapHorizontal = null;
  25551. this.vsmMaterialHorizontal.dispose();
  25552. this.vsmMaterialHorizontal = null;
  25553. }
  25554. super.dispose();
  25555. }
  25556. /**
  25557. * The implementation performs the update of the shadow map if necessary.
  25558. *
  25559. * @param {NodeFrame} frame - A reference to the current node frame.
  25560. */
  25561. updateBefore( frame ) {
  25562. const { shadow } = this;
  25563. const needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  25564. if ( needsUpdate ) {
  25565. this.updateShadow( frame );
  25566. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  25567. shadow.needsUpdate = false;
  25568. }
  25569. }
  25570. }
  25571. }
  25572. /**
  25573. * TSL function for creating an instance of `ShadowNode`.
  25574. *
  25575. * @function
  25576. * @param {Light} light - The shadow casting light.
  25577. * @param {LightShadow} shadow - The light shadow.
  25578. * @return {ShadowNode} The created shadow node.
  25579. */
  25580. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  25581. /**
  25582. * Base class for analytic light nodes.
  25583. *
  25584. * @augments LightingNode
  25585. */
  25586. class AnalyticLightNode extends LightingNode {
  25587. static get type() {
  25588. return 'AnalyticLightNode';
  25589. }
  25590. /**
  25591. * Constructs a new analytic light node.
  25592. *
  25593. * @param {Light?} [light=null] - The light source.
  25594. */
  25595. constructor( light = null ) {
  25596. super();
  25597. /**
  25598. * The light source.
  25599. *
  25600. * @type {Light?}
  25601. * @default null
  25602. */
  25603. this.light = light;
  25604. /**
  25605. * The light's color value.
  25606. *
  25607. * @type {Color}
  25608. */
  25609. this.color = new Color();
  25610. /**
  25611. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  25612. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  25613. *
  25614. * @type {Node}
  25615. */
  25616. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  25617. /**
  25618. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  25619. * The final color node is represented by a different node when using shadows.
  25620. *
  25621. * @type {Node?}
  25622. * @default null
  25623. */
  25624. this.baseColorNode = null;
  25625. /**
  25626. * Represents the light's shadow.
  25627. *
  25628. * @type {ShadowNode?}
  25629. * @default null
  25630. */
  25631. this.shadowNode = null;
  25632. /**
  25633. * Represents the light's shadow color.
  25634. *
  25635. * @type {Node?}
  25636. * @default null
  25637. */
  25638. this.shadowColorNode = null;
  25639. /**
  25640. * This flag can be used for type testing.
  25641. *
  25642. * @type {Boolean}
  25643. * @readonly
  25644. * @default true
  25645. */
  25646. this.isAnalyticLightNode = true;
  25647. /**
  25648. * Overwritten since analytic light nodes are updated
  25649. * once per frame.
  25650. *
  25651. * @type {String}
  25652. * @default 'frame'
  25653. */
  25654. this.updateType = NodeUpdateType.FRAME;
  25655. }
  25656. /**
  25657. * Overwrites the default {@link Node#customCacheKey} implementation by including the
  25658. * `light.id` and `light.castShadow` into the cache key.
  25659. *
  25660. * @return {Number} The custom cache key.
  25661. */
  25662. customCacheKey() {
  25663. return hash$1( this.light.id, this.light.castShadow ? 1 : 0 );
  25664. }
  25665. getHash() {
  25666. return this.light.uuid;
  25667. }
  25668. /**
  25669. * Setups the shadow node for this light. The method exists so concrete light classes
  25670. * can setup different types of shadow nodes.
  25671. *
  25672. * @return {ShadowNode} The created shadow node.
  25673. */
  25674. setupShadowNode() {
  25675. return shadow( this.light );
  25676. }
  25677. /**
  25678. * Setups the shadow for this light. This method is only executed if the light
  25679. * cast shadows and the current build object receives shadows. It incorporates
  25680. * shadows into the lighting computation.
  25681. *
  25682. * @param {NodeBuilder} builder - The current node builder.
  25683. */
  25684. setupShadow( builder ) {
  25685. const { renderer } = builder;
  25686. if ( renderer.shadowMap.enabled === false ) return;
  25687. let shadowColorNode = this.shadowColorNode;
  25688. if ( shadowColorNode === null ) {
  25689. const customShadowNode = this.light.shadow.shadowNode;
  25690. let shadowNode;
  25691. if ( customShadowNode !== undefined ) {
  25692. shadowNode = nodeObject( customShadowNode );
  25693. } else {
  25694. shadowNode = this.setupShadowNode( builder );
  25695. }
  25696. this.shadowNode = shadowNode;
  25697. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  25698. this.baseColorNode = this.colorNode;
  25699. }
  25700. //
  25701. this.colorNode = shadowColorNode;
  25702. }
  25703. /**
  25704. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  25705. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  25706. * invocate the respective interface methods.
  25707. *
  25708. * @param {NodeBuilder} builder - The current node builder.
  25709. */
  25710. setup( builder ) {
  25711. this.colorNode = this.baseColorNode || this.colorNode;
  25712. if ( this.light.castShadow ) {
  25713. if ( builder.object.receiveShadow ) {
  25714. this.setupShadow( builder );
  25715. }
  25716. } else if ( this.shadowNode !== null ) {
  25717. this.shadowNode.dispose();
  25718. this.shadowNode = null;
  25719. this.shadowColorNode = null;
  25720. }
  25721. }
  25722. /**
  25723. * The update method is used to update light uniforms per frame.
  25724. * Potentially overwritten in concrete light nodes to update light
  25725. * specific uniforms.
  25726. *
  25727. * @param {NodeFrame} frame - A reference to the current node frame.
  25728. */
  25729. update( /*frame*/ ) {
  25730. const { light } = this;
  25731. this.color.copy( light.color ).multiplyScalar( light.intensity );
  25732. }
  25733. }
  25734. /** @module LightUtils **/
  25735. /**
  25736. * Represents a `discard` shader operation in TSL.
  25737. *
  25738. * @method
  25739. * @param {Object} inputs - The input parameter object.
  25740. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  25741. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  25742. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  25743. * @return {Node<float>} The distance falloff.
  25744. */
  25745. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( inputs ) => {
  25746. const { lightDistance, cutoffDistance, decayExponent } = inputs;
  25747. // based upon Frostbite 3 Moving to Physically-based Rendering
  25748. // page 32, equation 26: E[window1]
  25749. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  25750. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  25751. return cutoffDistance.greaterThan( 0 ).select(
  25752. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  25753. distanceFalloff
  25754. );
  25755. } ); // validated
  25756. /** @module PointShadowNode **/
  25757. const _clearColor$2 = /*@__PURE__*/ new Color();
  25758. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  25759. // vector suitable for 2D texture mapping. This code uses the following layout for the
  25760. // 2D texture:
  25761. //
  25762. // xzXZ
  25763. // y Y
  25764. //
  25765. // Y - Positive y direction
  25766. // y - Negative y direction
  25767. // X - Positive x direction
  25768. // x - Negative x direction
  25769. // Z - Positive z direction
  25770. // z - Negative z direction
  25771. //
  25772. // Source and test bed:
  25773. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  25774. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  25775. const v = pos.toVar();
  25776. // Number of texels to avoid at the edge of each square
  25777. const absV = abs( v );
  25778. // Intersect unit cube
  25779. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  25780. absV.mulAssign( scaleToCube );
  25781. // Apply scale to avoid seams
  25782. // two texels less per square (one texel will do for NEAREST)
  25783. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  25784. // Unwrap
  25785. // space: -1 ... 1 range for each square
  25786. //
  25787. // #X## dim := ( 4 , 2 )
  25788. // # # center := ( 1 , 1 )
  25789. const planar = vec2( v.xy ).toVar();
  25790. const almostATexel = texelSizeY.mul( 1.5 );
  25791. const almostOne = almostATexel.oneMinus();
  25792. If( absV.z.greaterThanEqual( almostOne ), () => {
  25793. If( v.z.greaterThan( 0.0 ), () => {
  25794. planar.x.assign( sub( 4.0, v.x ) );
  25795. } );
  25796. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  25797. const signX = sign( v.x );
  25798. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  25799. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  25800. const signY = sign( v.y );
  25801. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  25802. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  25803. } );
  25804. // Transform to UV space
  25805. // scale := 0.5 / dim
  25806. // translate := ( center + 0.5 ) / dim
  25807. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  25808. } ).setLayout( {
  25809. name: 'cubeToUV',
  25810. type: 'vec2',
  25811. inputs: [
  25812. { name: 'pos', type: 'vec3' },
  25813. { name: 'texelSizeY', type: 'float' }
  25814. ]
  25815. } );
  25816. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  25817. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  25818. } );
  25819. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  25820. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  25821. const offset = vec2( - 1.0, 1.0 ).mul( radius ).mul( texelSize.y );
  25822. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  25823. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  25824. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  25825. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  25826. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  25827. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  25828. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  25829. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  25830. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  25831. .mul( 1.0 / 9.0 );
  25832. } );
  25833. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  25834. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  25835. // the vector from the light to the world-space position of the fragment.
  25836. const lightToPosition = shadowCoord.xyz.toVar();
  25837. const lightToPositionLength = lightToPosition.length();
  25838. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  25839. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  25840. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  25841. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  25842. const result = float( 1.0 ).toVar();
  25843. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  25844. // dp = normalized distance from light to fragment position
  25845. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  25846. dp.addAssign( bias );
  25847. // bd3D = base direction 3D
  25848. const bd3D = lightToPosition.normalize();
  25849. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  25850. // percentage-closer filtering
  25851. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  25852. } );
  25853. return result;
  25854. } );
  25855. const _viewport = /*@__PURE__*/ new Vector4();
  25856. const _viewportSize = /*@__PURE__*/ new Vector2();
  25857. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  25858. /**
  25859. * Represents the shadow implementation for point light nodes.
  25860. *
  25861. * @augments module:ShadowNode~ShadowNode
  25862. */
  25863. class PointShadowNode extends ShadowNode {
  25864. static get type() {
  25865. return 'PointShadowNode';
  25866. }
  25867. /**
  25868. * Constructs a new point shadow node.
  25869. *
  25870. * @param {PointLight} light - The shadow casting point light.
  25871. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25872. */
  25873. constructor( light, shadow = null ) {
  25874. super( light, shadow );
  25875. }
  25876. /**
  25877. * Overwrites the default implementation to return point light shadow specific
  25878. * filtering functions.
  25879. *
  25880. * @param {Number} type - The shadow type.
  25881. * @return {Function} The filtering function.
  25882. */
  25883. getShadowFilterFn( type ) {
  25884. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  25885. }
  25886. /**
  25887. * Overwrites the default implementation so the unaltered shadow position is used.
  25888. *
  25889. * @param {NodeBuilder} builder - A reference to the current node builder.
  25890. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  25891. * @return {Node<vec3>} The shadow coordinates.
  25892. */
  25893. setupShadowCoord( builder, shadowPosition ) {
  25894. return shadowPosition;
  25895. }
  25896. /**
  25897. * Overwrites the default implementation to only use point light specific
  25898. * shadow filter functions.
  25899. *
  25900. * @param {NodeBuilder} builder - A reference to the current node builder.
  25901. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  25902. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  25903. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  25904. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  25905. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  25906. * @param {LightShadow} inputs.shadow - The light shadow.
  25907. * @return {Node<float>} The result node of the shadow filtering.
  25908. */
  25909. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  25910. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  25911. }
  25912. /**
  25913. * Overwrites the default implementation with point light specific
  25914. * rendering code.
  25915. *
  25916. * @param {NodeFrame} frame - A reference to the current node frame.
  25917. */
  25918. renderShadow( frame ) {
  25919. const { shadow, shadowMap, light } = this;
  25920. const { renderer, scene } = frame;
  25921. const shadowFrameExtents = shadow.getFrameExtents();
  25922. _shadowMapSize.copy( shadow.mapSize );
  25923. _shadowMapSize.multiply( shadowFrameExtents );
  25924. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  25925. _viewportSize.copy( shadow.mapSize );
  25926. //
  25927. const previousAutoClear = renderer.autoClear;
  25928. const previousClearColor = renderer.getClearColor( _clearColor$2 );
  25929. const previousClearAlpha = renderer.getClearAlpha();
  25930. renderer.autoClear = false;
  25931. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  25932. renderer.clear();
  25933. const viewportCount = shadow.getViewportCount();
  25934. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  25935. const viewport = shadow.getViewport( vp );
  25936. const x = _viewportSize.x * viewport.x;
  25937. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  25938. _viewport.set(
  25939. x,
  25940. y,
  25941. _viewportSize.x * viewport.z,
  25942. _viewportSize.y * viewport.w
  25943. );
  25944. shadowMap.viewport.copy( _viewport );
  25945. shadow.updateMatrices( light, vp );
  25946. renderer.render( scene, shadow.camera );
  25947. }
  25948. //
  25949. renderer.autoClear = previousAutoClear;
  25950. renderer.setClearColor( previousClearColor, previousClearAlpha );
  25951. }
  25952. }
  25953. /**
  25954. * TSL function for creating an instance of `PointShadowNode`.
  25955. *
  25956. * @function
  25957. * @param {PointLight} light - The shadow casting point light.
  25958. * @param {PointLightShadow?} [shadow=null] - An optional point light shadow.
  25959. * @return {PointShadowNode} The created point shadow node.
  25960. */
  25961. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  25962. const directPointLight = Fn( ( { color, lightViewPosition, cutoffDistance, decayExponent }, builder ) => {
  25963. const lightingModel = builder.context.lightingModel;
  25964. const lVector = lightViewPosition.sub( positionView ); // @TODO: Add it into LightNode
  25965. const lightDirection = lVector.normalize();
  25966. const lightDistance = lVector.length();
  25967. const lightAttenuation = getDistanceAttenuation( {
  25968. lightDistance,
  25969. cutoffDistance,
  25970. decayExponent
  25971. } );
  25972. const lightColor = color.mul( lightAttenuation );
  25973. const reflectedLight = builder.context.reflectedLight;
  25974. lightingModel.direct( {
  25975. lightDirection,
  25976. lightColor,
  25977. reflectedLight
  25978. }, builder.stack, builder );
  25979. } );
  25980. /**
  25981. * Module for representing point lights as nodes.
  25982. *
  25983. * @augments AnalyticLightNode
  25984. */
  25985. class PointLightNode extends AnalyticLightNode {
  25986. static get type() {
  25987. return 'PointLightNode';
  25988. }
  25989. /**
  25990. * Constructs a new point light node.
  25991. *
  25992. * @param {PointLight?} [light=null] - The point light source.
  25993. */
  25994. constructor( light = null ) {
  25995. super( light );
  25996. /**
  25997. * Uniform node representing the cutoff distance.
  25998. *
  25999. * @type {UniformNode<float>}
  26000. */
  26001. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  26002. /**
  26003. * Uniform node representing the decay exponent.
  26004. *
  26005. * @type {UniformNode<float>}
  26006. */
  26007. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  26008. }
  26009. /**
  26010. * Overwritten to updated point light specific uniforms.
  26011. *
  26012. * @param {NodeFrame} frame - A reference to the current node frame.
  26013. */
  26014. update( frame ) {
  26015. const { light } = this;
  26016. super.update( frame );
  26017. this.cutoffDistanceNode.value = light.distance;
  26018. this.decayExponentNode.value = light.decay;
  26019. }
  26020. /**
  26021. * Overwritten to setup point light specific shadow.
  26022. *
  26023. * @return {PointShadowNode}
  26024. */
  26025. setupShadowNode() {
  26026. return pointShadow( this.light );
  26027. }
  26028. setup( builder ) {
  26029. super.setup( builder );
  26030. directPointLight( {
  26031. color: this.colorNode,
  26032. lightViewPosition: lightViewPosition( this.light ),
  26033. cutoffDistance: this.cutoffDistanceNode,
  26034. decayExponent: this.decayExponentNode
  26035. } ).append();
  26036. }
  26037. }
  26038. /** @module Procedural **/
  26039. /**
  26040. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  26041. *
  26042. * @method
  26043. * @param {Node<vec2>} coord - The uv coordinates.
  26044. * @return {Node<float>} The result data.
  26045. */
  26046. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  26047. const uv = coord.mul( 2.0 );
  26048. const cx = uv.x.floor();
  26049. const cy = uv.y.floor();
  26050. const result = cx.add( cy ).mod( 2.0 );
  26051. return result.sign();
  26052. } );
  26053. /** @module Shapes **/
  26054. /**
  26055. * Generates a circle based on the uv coordinates.
  26056. *
  26057. * @method
  26058. * @param {Node<vec2>} coord - The uv to generate the circle.
  26059. * @return {Node<float>} The circle shape.
  26060. */
  26061. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  26062. const alpha = float( 1 ).toVar();
  26063. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  26064. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  26065. const dlen = float( len2.fwidth() ).toVar();
  26066. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  26067. } else {
  26068. len2.greaterThan( 1.0 ).discard();
  26069. }
  26070. return alpha;
  26071. } );
  26072. // Three.js Transpiler
  26073. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  26074. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  26075. const f = float( f_immutable ).toVar();
  26076. const t = float( t_immutable ).toVar();
  26077. const b = bool( b_immutable ).toVar();
  26078. return select( b, t, f );
  26079. } ).setLayout( {
  26080. name: 'mx_select',
  26081. type: 'float',
  26082. inputs: [
  26083. { name: 'b', type: 'bool' },
  26084. { name: 't', type: 'float' },
  26085. { name: 'f', type: 'float' }
  26086. ]
  26087. } );
  26088. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  26089. const b = bool( b_immutable ).toVar();
  26090. const val = float( val_immutable ).toVar();
  26091. return select( b, val.negate(), val );
  26092. } ).setLayout( {
  26093. name: 'mx_negate_if',
  26094. type: 'float',
  26095. inputs: [
  26096. { name: 'val', type: 'float' },
  26097. { name: 'b', type: 'bool' }
  26098. ]
  26099. } );
  26100. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26101. const x = float( x_immutable ).toVar();
  26102. return int( floor( x ) );
  26103. } ).setLayout( {
  26104. name: 'mx_floor',
  26105. type: 'int',
  26106. inputs: [
  26107. { name: 'x', type: 'float' }
  26108. ]
  26109. } );
  26110. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  26111. const x = float( x_immutable ).toVar();
  26112. i.assign( mx_floor( x ) );
  26113. return x.sub( float( i ) );
  26114. } );
  26115. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26116. const t = float( t_immutable ).toVar();
  26117. const s = float( s_immutable ).toVar();
  26118. const v3 = float( v3_immutable ).toVar();
  26119. const v2 = float( v2_immutable ).toVar();
  26120. const v1 = float( v1_immutable ).toVar();
  26121. const v0 = float( v0_immutable ).toVar();
  26122. const s1 = float( sub( 1.0, s ) ).toVar();
  26123. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26124. } ).setLayout( {
  26125. name: 'mx_bilerp_0',
  26126. type: 'float',
  26127. inputs: [
  26128. { name: 'v0', type: 'float' },
  26129. { name: 'v1', type: 'float' },
  26130. { name: 'v2', type: 'float' },
  26131. { name: 'v3', type: 'float' },
  26132. { name: 's', type: 'float' },
  26133. { name: 't', type: 'float' }
  26134. ]
  26135. } );
  26136. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  26137. const t = float( t_immutable ).toVar();
  26138. const s = float( s_immutable ).toVar();
  26139. const v3 = vec3( v3_immutable ).toVar();
  26140. const v2 = vec3( v2_immutable ).toVar();
  26141. const v1 = vec3( v1_immutable ).toVar();
  26142. const v0 = vec3( v0_immutable ).toVar();
  26143. const s1 = float( sub( 1.0, s ) ).toVar();
  26144. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  26145. } ).setLayout( {
  26146. name: 'mx_bilerp_1',
  26147. type: 'vec3',
  26148. inputs: [
  26149. { name: 'v0', type: 'vec3' },
  26150. { name: 'v1', type: 'vec3' },
  26151. { name: 'v2', type: 'vec3' },
  26152. { name: 'v3', type: 'vec3' },
  26153. { name: 's', type: 'float' },
  26154. { name: 't', type: 'float' }
  26155. ]
  26156. } );
  26157. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  26158. 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 ] ) => {
  26159. const r = float( r_immutable ).toVar();
  26160. const t = float( t_immutable ).toVar();
  26161. const s = float( s_immutable ).toVar();
  26162. const v7 = float( v7_immutable ).toVar();
  26163. const v6 = float( v6_immutable ).toVar();
  26164. const v5 = float( v5_immutable ).toVar();
  26165. const v4 = float( v4_immutable ).toVar();
  26166. const v3 = float( v3_immutable ).toVar();
  26167. const v2 = float( v2_immutable ).toVar();
  26168. const v1 = float( v1_immutable ).toVar();
  26169. const v0 = float( v0_immutable ).toVar();
  26170. const s1 = float( sub( 1.0, s ) ).toVar();
  26171. const t1 = float( sub( 1.0, t ) ).toVar();
  26172. const r1 = float( sub( 1.0, r ) ).toVar();
  26173. 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 ) ) ) ) ) );
  26174. } ).setLayout( {
  26175. name: 'mx_trilerp_0',
  26176. type: 'float',
  26177. inputs: [
  26178. { name: 'v0', type: 'float' },
  26179. { name: 'v1', type: 'float' },
  26180. { name: 'v2', type: 'float' },
  26181. { name: 'v3', type: 'float' },
  26182. { name: 'v4', type: 'float' },
  26183. { name: 'v5', type: 'float' },
  26184. { name: 'v6', type: 'float' },
  26185. { name: 'v7', type: 'float' },
  26186. { name: 's', type: 'float' },
  26187. { name: 't', type: 'float' },
  26188. { name: 'r', type: 'float' }
  26189. ]
  26190. } );
  26191. 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 ] ) => {
  26192. const r = float( r_immutable ).toVar();
  26193. const t = float( t_immutable ).toVar();
  26194. const s = float( s_immutable ).toVar();
  26195. const v7 = vec3( v7_immutable ).toVar();
  26196. const v6 = vec3( v6_immutable ).toVar();
  26197. const v5 = vec3( v5_immutable ).toVar();
  26198. const v4 = vec3( v4_immutable ).toVar();
  26199. const v3 = vec3( v3_immutable ).toVar();
  26200. const v2 = vec3( v2_immutable ).toVar();
  26201. const v1 = vec3( v1_immutable ).toVar();
  26202. const v0 = vec3( v0_immutable ).toVar();
  26203. const s1 = float( sub( 1.0, s ) ).toVar();
  26204. const t1 = float( sub( 1.0, t ) ).toVar();
  26205. const r1 = float( sub( 1.0, r ) ).toVar();
  26206. 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 ) ) ) ) ) );
  26207. } ).setLayout( {
  26208. name: 'mx_trilerp_1',
  26209. type: 'vec3',
  26210. inputs: [
  26211. { name: 'v0', type: 'vec3' },
  26212. { name: 'v1', type: 'vec3' },
  26213. { name: 'v2', type: 'vec3' },
  26214. { name: 'v3', type: 'vec3' },
  26215. { name: 'v4', type: 'vec3' },
  26216. { name: 'v5', type: 'vec3' },
  26217. { name: 'v6', type: 'vec3' },
  26218. { name: 'v7', type: 'vec3' },
  26219. { name: 's', type: 'float' },
  26220. { name: 't', type: 'float' },
  26221. { name: 'r', type: 'float' }
  26222. ]
  26223. } );
  26224. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  26225. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26226. const y = float( y_immutable ).toVar();
  26227. const x = float( x_immutable ).toVar();
  26228. const hash = uint( hash_immutable ).toVar();
  26229. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  26230. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  26231. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  26232. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26233. } ).setLayout( {
  26234. name: 'mx_gradient_float_0',
  26235. type: 'float',
  26236. inputs: [
  26237. { name: 'hash', type: 'uint' },
  26238. { name: 'x', type: 'float' },
  26239. { name: 'y', type: 'float' }
  26240. ]
  26241. } );
  26242. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26243. const z = float( z_immutable ).toVar();
  26244. const y = float( y_immutable ).toVar();
  26245. const x = float( x_immutable ).toVar();
  26246. const hash = uint( hash_immutable ).toVar();
  26247. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  26248. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  26249. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  26250. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  26251. } ).setLayout( {
  26252. name: 'mx_gradient_float_1',
  26253. type: 'float',
  26254. inputs: [
  26255. { name: 'hash', type: 'uint' },
  26256. { name: 'x', type: 'float' },
  26257. { name: 'y', type: 'float' },
  26258. { name: 'z', type: 'float' }
  26259. ]
  26260. } );
  26261. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  26262. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  26263. const y = float( y_immutable ).toVar();
  26264. const x = float( x_immutable ).toVar();
  26265. const hash = uvec3( hash_immutable ).toVar();
  26266. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  26267. } ).setLayout( {
  26268. name: 'mx_gradient_vec3_0',
  26269. type: 'vec3',
  26270. inputs: [
  26271. { name: 'hash', type: 'uvec3' },
  26272. { name: 'x', type: 'float' },
  26273. { name: 'y', type: 'float' }
  26274. ]
  26275. } );
  26276. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  26277. const z = float( z_immutable ).toVar();
  26278. const y = float( y_immutable ).toVar();
  26279. const x = float( x_immutable ).toVar();
  26280. const hash = uvec3( hash_immutable ).toVar();
  26281. 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 ) );
  26282. } ).setLayout( {
  26283. name: 'mx_gradient_vec3_1',
  26284. type: 'vec3',
  26285. inputs: [
  26286. { name: 'hash', type: 'uvec3' },
  26287. { name: 'x', type: 'float' },
  26288. { name: 'y', type: 'float' },
  26289. { name: 'z', type: 'float' }
  26290. ]
  26291. } );
  26292. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  26293. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26294. const v = float( v_immutable ).toVar();
  26295. return mul( 0.6616, v );
  26296. } ).setLayout( {
  26297. name: 'mx_gradient_scale2d_0',
  26298. type: 'float',
  26299. inputs: [
  26300. { name: 'v', type: 'float' }
  26301. ]
  26302. } );
  26303. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26304. const v = float( v_immutable ).toVar();
  26305. return mul( 0.9820, v );
  26306. } ).setLayout( {
  26307. name: 'mx_gradient_scale3d_0',
  26308. type: 'float',
  26309. inputs: [
  26310. { name: 'v', type: 'float' }
  26311. ]
  26312. } );
  26313. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26314. const v = vec3( v_immutable ).toVar();
  26315. return mul( 0.6616, v );
  26316. } ).setLayout( {
  26317. name: 'mx_gradient_scale2d_1',
  26318. type: 'vec3',
  26319. inputs: [
  26320. { name: 'v', type: 'vec3' }
  26321. ]
  26322. } );
  26323. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  26324. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  26325. const v = vec3( v_immutable ).toVar();
  26326. return mul( 0.9820, v );
  26327. } ).setLayout( {
  26328. name: 'mx_gradient_scale3d_1',
  26329. type: 'vec3',
  26330. inputs: [
  26331. { name: 'v', type: 'vec3' }
  26332. ]
  26333. } );
  26334. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  26335. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  26336. const k = int( k_immutable ).toVar();
  26337. const x = uint( x_immutable ).toVar();
  26338. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  26339. } ).setLayout( {
  26340. name: 'mx_rotl32',
  26341. type: 'uint',
  26342. inputs: [
  26343. { name: 'x', type: 'uint' },
  26344. { name: 'k', type: 'int' }
  26345. ]
  26346. } );
  26347. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  26348. a.subAssign( c );
  26349. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  26350. c.addAssign( b );
  26351. b.subAssign( a );
  26352. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  26353. a.addAssign( c );
  26354. c.subAssign( b );
  26355. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  26356. b.addAssign( a );
  26357. a.subAssign( c );
  26358. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  26359. c.addAssign( b );
  26360. b.subAssign( a );
  26361. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  26362. a.addAssign( c );
  26363. c.subAssign( b );
  26364. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  26365. b.addAssign( a );
  26366. } );
  26367. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  26368. const c = uint( c_immutable ).toVar();
  26369. const b = uint( b_immutable ).toVar();
  26370. const a = uint( a_immutable ).toVar();
  26371. c.bitXorAssign( b );
  26372. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  26373. a.bitXorAssign( c );
  26374. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  26375. b.bitXorAssign( a );
  26376. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  26377. c.bitXorAssign( b );
  26378. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  26379. a.bitXorAssign( c );
  26380. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  26381. b.bitXorAssign( a );
  26382. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  26383. c.bitXorAssign( b );
  26384. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  26385. return c;
  26386. } ).setLayout( {
  26387. name: 'mx_bjfinal',
  26388. type: 'uint',
  26389. inputs: [
  26390. { name: 'a', type: 'uint' },
  26391. { name: 'b', type: 'uint' },
  26392. { name: 'c', type: 'uint' }
  26393. ]
  26394. } );
  26395. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  26396. const bits = uint( bits_immutable ).toVar();
  26397. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  26398. } ).setLayout( {
  26399. name: 'mx_bits_to_01',
  26400. type: 'float',
  26401. inputs: [
  26402. { name: 'bits', type: 'uint' }
  26403. ]
  26404. } );
  26405. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  26406. const t = float( t_immutable ).toVar();
  26407. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  26408. } ).setLayout( {
  26409. name: 'mx_fade',
  26410. type: 'float',
  26411. inputs: [
  26412. { name: 't', type: 'float' }
  26413. ]
  26414. } );
  26415. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26416. const x = int( x_immutable ).toVar();
  26417. const len = uint( uint( 1 ) ).toVar();
  26418. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  26419. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  26420. } ).setLayout( {
  26421. name: 'mx_hash_int_0',
  26422. type: 'uint',
  26423. inputs: [
  26424. { name: 'x', type: 'int' }
  26425. ]
  26426. } );
  26427. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26428. const y = int( y_immutable ).toVar();
  26429. const x = int( x_immutable ).toVar();
  26430. const len = uint( uint( 2 ) ).toVar();
  26431. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26432. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26433. a.addAssign( uint( x ) );
  26434. b.addAssign( uint( y ) );
  26435. return mx_bjfinal( a, b, c );
  26436. } ).setLayout( {
  26437. name: 'mx_hash_int_1',
  26438. type: 'uint',
  26439. inputs: [
  26440. { name: 'x', type: 'int' },
  26441. { name: 'y', type: 'int' }
  26442. ]
  26443. } );
  26444. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26445. const z = int( z_immutable ).toVar();
  26446. const y = int( y_immutable ).toVar();
  26447. const x = int( x_immutable ).toVar();
  26448. const len = uint( uint( 3 ) ).toVar();
  26449. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26450. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26451. a.addAssign( uint( x ) );
  26452. b.addAssign( uint( y ) );
  26453. c.addAssign( uint( z ) );
  26454. return mx_bjfinal( a, b, c );
  26455. } ).setLayout( {
  26456. name: 'mx_hash_int_2',
  26457. type: 'uint',
  26458. inputs: [
  26459. { name: 'x', type: 'int' },
  26460. { name: 'y', type: 'int' },
  26461. { name: 'z', type: 'int' }
  26462. ]
  26463. } );
  26464. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  26465. const xx = int( xx_immutable ).toVar();
  26466. const z = int( z_immutable ).toVar();
  26467. const y = int( y_immutable ).toVar();
  26468. const x = int( x_immutable ).toVar();
  26469. const len = uint( uint( 4 ) ).toVar();
  26470. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26471. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26472. a.addAssign( uint( x ) );
  26473. b.addAssign( uint( y ) );
  26474. c.addAssign( uint( z ) );
  26475. mx_bjmix( a, b, c );
  26476. a.addAssign( uint( xx ) );
  26477. return mx_bjfinal( a, b, c );
  26478. } ).setLayout( {
  26479. name: 'mx_hash_int_3',
  26480. type: 'uint',
  26481. inputs: [
  26482. { name: 'x', type: 'int' },
  26483. { name: 'y', type: 'int' },
  26484. { name: 'z', type: 'int' },
  26485. { name: 'xx', type: 'int' }
  26486. ]
  26487. } );
  26488. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  26489. const yy = int( yy_immutable ).toVar();
  26490. const xx = int( xx_immutable ).toVar();
  26491. const z = int( z_immutable ).toVar();
  26492. const y = int( y_immutable ).toVar();
  26493. const x = int( x_immutable ).toVar();
  26494. const len = uint( uint( 5 ) ).toVar();
  26495. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  26496. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  26497. a.addAssign( uint( x ) );
  26498. b.addAssign( uint( y ) );
  26499. c.addAssign( uint( z ) );
  26500. mx_bjmix( a, b, c );
  26501. a.addAssign( uint( xx ) );
  26502. b.addAssign( uint( yy ) );
  26503. return mx_bjfinal( a, b, c );
  26504. } ).setLayout( {
  26505. name: 'mx_hash_int_4',
  26506. type: 'uint',
  26507. inputs: [
  26508. { name: 'x', type: 'int' },
  26509. { name: 'y', type: 'int' },
  26510. { name: 'z', type: 'int' },
  26511. { name: 'xx', type: 'int' },
  26512. { name: 'yy', type: 'int' }
  26513. ]
  26514. } );
  26515. 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 ] );
  26516. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  26517. const y = int( y_immutable ).toVar();
  26518. const x = int( x_immutable ).toVar();
  26519. const h = uint( mx_hash_int( x, y ) ).toVar();
  26520. const result = uvec3().toVar();
  26521. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26522. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26523. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26524. return result;
  26525. } ).setLayout( {
  26526. name: 'mx_hash_vec3_0',
  26527. type: 'uvec3',
  26528. inputs: [
  26529. { name: 'x', type: 'int' },
  26530. { name: 'y', type: 'int' }
  26531. ]
  26532. } );
  26533. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  26534. const z = int( z_immutable ).toVar();
  26535. const y = int( y_immutable ).toVar();
  26536. const x = int( x_immutable ).toVar();
  26537. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  26538. const result = uvec3().toVar();
  26539. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  26540. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  26541. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  26542. return result;
  26543. } ).setLayout( {
  26544. name: 'mx_hash_vec3_1',
  26545. type: 'uvec3',
  26546. inputs: [
  26547. { name: 'x', type: 'int' },
  26548. { name: 'y', type: 'int' },
  26549. { name: 'z', type: 'int' }
  26550. ]
  26551. } );
  26552. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  26553. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26554. const p = vec2( p_immutable ).toVar();
  26555. const X = int().toVar(), Y = int().toVar();
  26556. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26557. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26558. const u = float( mx_fade( fx ) ).toVar();
  26559. const v = float( mx_fade( fy ) ).toVar();
  26560. 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();
  26561. return mx_gradient_scale2d( result );
  26562. } ).setLayout( {
  26563. name: 'mx_perlin_noise_float_0',
  26564. type: 'float',
  26565. inputs: [
  26566. { name: 'p', type: 'vec2' }
  26567. ]
  26568. } );
  26569. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26570. const p = vec3( p_immutable ).toVar();
  26571. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26572. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26573. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26574. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26575. const u = float( mx_fade( fx ) ).toVar();
  26576. const v = float( mx_fade( fy ) ).toVar();
  26577. const w = float( mx_fade( fz ) ).toVar();
  26578. 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();
  26579. return mx_gradient_scale3d( result );
  26580. } ).setLayout( {
  26581. name: 'mx_perlin_noise_float_1',
  26582. type: 'float',
  26583. inputs: [
  26584. { name: 'p', type: 'vec3' }
  26585. ]
  26586. } );
  26587. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  26588. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26589. const p = vec2( p_immutable ).toVar();
  26590. const X = int().toVar(), Y = int().toVar();
  26591. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26592. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26593. const u = float( mx_fade( fx ) ).toVar();
  26594. const v = float( mx_fade( fy ) ).toVar();
  26595. 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();
  26596. return mx_gradient_scale2d( result );
  26597. } ).setLayout( {
  26598. name: 'mx_perlin_noise_vec3_0',
  26599. type: 'vec3',
  26600. inputs: [
  26601. { name: 'p', type: 'vec2' }
  26602. ]
  26603. } );
  26604. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26605. const p = vec3( p_immutable ).toVar();
  26606. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26607. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  26608. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  26609. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  26610. const u = float( mx_fade( fx ) ).toVar();
  26611. const v = float( mx_fade( fy ) ).toVar();
  26612. const w = float( mx_fade( fz ) ).toVar();
  26613. 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();
  26614. return mx_gradient_scale3d( result );
  26615. } ).setLayout( {
  26616. name: 'mx_perlin_noise_vec3_1',
  26617. type: 'vec3',
  26618. inputs: [
  26619. { name: 'p', type: 'vec3' }
  26620. ]
  26621. } );
  26622. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  26623. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26624. const p = float( p_immutable ).toVar();
  26625. const ix = int( mx_floor( p ) ).toVar();
  26626. return mx_bits_to_01( mx_hash_int( ix ) );
  26627. } ).setLayout( {
  26628. name: 'mx_cell_noise_float_0',
  26629. type: 'float',
  26630. inputs: [
  26631. { name: 'p', type: 'float' }
  26632. ]
  26633. } );
  26634. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26635. const p = vec2( p_immutable ).toVar();
  26636. const ix = int( mx_floor( p.x ) ).toVar();
  26637. const iy = int( mx_floor( p.y ) ).toVar();
  26638. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  26639. } ).setLayout( {
  26640. name: 'mx_cell_noise_float_1',
  26641. type: 'float',
  26642. inputs: [
  26643. { name: 'p', type: 'vec2' }
  26644. ]
  26645. } );
  26646. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26647. const p = vec3( p_immutable ).toVar();
  26648. const ix = int( mx_floor( p.x ) ).toVar();
  26649. const iy = int( mx_floor( p.y ) ).toVar();
  26650. const iz = int( mx_floor( p.z ) ).toVar();
  26651. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  26652. } ).setLayout( {
  26653. name: 'mx_cell_noise_float_2',
  26654. type: 'float',
  26655. inputs: [
  26656. { name: 'p', type: 'vec3' }
  26657. ]
  26658. } );
  26659. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26660. const p = vec4( p_immutable ).toVar();
  26661. const ix = int( mx_floor( p.x ) ).toVar();
  26662. const iy = int( mx_floor( p.y ) ).toVar();
  26663. const iz = int( mx_floor( p.z ) ).toVar();
  26664. const iw = int( mx_floor( p.w ) ).toVar();
  26665. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  26666. } ).setLayout( {
  26667. name: 'mx_cell_noise_float_3',
  26668. type: 'float',
  26669. inputs: [
  26670. { name: 'p', type: 'vec4' }
  26671. ]
  26672. } );
  26673. 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 ] );
  26674. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26675. const p = float( p_immutable ).toVar();
  26676. const ix = int( mx_floor( p ) ).toVar();
  26677. 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 ) ) ) );
  26678. } ).setLayout( {
  26679. name: 'mx_cell_noise_vec3_0',
  26680. type: 'vec3',
  26681. inputs: [
  26682. { name: 'p', type: 'float' }
  26683. ]
  26684. } );
  26685. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26686. const p = vec2( p_immutable ).toVar();
  26687. const ix = int( mx_floor( p.x ) ).toVar();
  26688. const iy = int( mx_floor( p.y ) ).toVar();
  26689. 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 ) ) ) );
  26690. } ).setLayout( {
  26691. name: 'mx_cell_noise_vec3_1',
  26692. type: 'vec3',
  26693. inputs: [
  26694. { name: 'p', type: 'vec2' }
  26695. ]
  26696. } );
  26697. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26698. const p = vec3( p_immutable ).toVar();
  26699. const ix = int( mx_floor( p.x ) ).toVar();
  26700. const iy = int( mx_floor( p.y ) ).toVar();
  26701. const iz = int( mx_floor( p.z ) ).toVar();
  26702. 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 ) ) ) );
  26703. } ).setLayout( {
  26704. name: 'mx_cell_noise_vec3_2',
  26705. type: 'vec3',
  26706. inputs: [
  26707. { name: 'p', type: 'vec3' }
  26708. ]
  26709. } );
  26710. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  26711. const p = vec4( p_immutable ).toVar();
  26712. const ix = int( mx_floor( p.x ) ).toVar();
  26713. const iy = int( mx_floor( p.y ) ).toVar();
  26714. const iz = int( mx_floor( p.z ) ).toVar();
  26715. const iw = int( mx_floor( p.w ) ).toVar();
  26716. 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 ) ) ) );
  26717. } ).setLayout( {
  26718. name: 'mx_cell_noise_vec3_3',
  26719. type: 'vec3',
  26720. inputs: [
  26721. { name: 'p', type: 'vec4' }
  26722. ]
  26723. } );
  26724. 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 ] );
  26725. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26726. const diminish = float( diminish_immutable ).toVar();
  26727. const lacunarity = float( lacunarity_immutable ).toVar();
  26728. const octaves = int( octaves_immutable ).toVar();
  26729. const p = vec3( p_immutable ).toVar();
  26730. const result = float( 0.0 ).toVar();
  26731. const amplitude = float( 1.0 ).toVar();
  26732. Loop( octaves, () => {
  26733. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  26734. amplitude.mulAssign( diminish );
  26735. p.mulAssign( lacunarity );
  26736. } );
  26737. return result;
  26738. } ).setLayout( {
  26739. name: 'mx_fractal_noise_float',
  26740. type: 'float',
  26741. inputs: [
  26742. { name: 'p', type: 'vec3' },
  26743. { name: 'octaves', type: 'int' },
  26744. { name: 'lacunarity', type: 'float' },
  26745. { name: 'diminish', type: 'float' }
  26746. ]
  26747. } );
  26748. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26749. const diminish = float( diminish_immutable ).toVar();
  26750. const lacunarity = float( lacunarity_immutable ).toVar();
  26751. const octaves = int( octaves_immutable ).toVar();
  26752. const p = vec3( p_immutable ).toVar();
  26753. const result = vec3( 0.0 ).toVar();
  26754. const amplitude = float( 1.0 ).toVar();
  26755. Loop( octaves, () => {
  26756. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  26757. amplitude.mulAssign( diminish );
  26758. p.mulAssign( lacunarity );
  26759. } );
  26760. return result;
  26761. } ).setLayout( {
  26762. name: 'mx_fractal_noise_vec3',
  26763. type: 'vec3',
  26764. inputs: [
  26765. { name: 'p', type: 'vec3' },
  26766. { name: 'octaves', type: 'int' },
  26767. { name: 'lacunarity', type: 'float' },
  26768. { name: 'diminish', type: 'float' }
  26769. ]
  26770. } );
  26771. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26772. const diminish = float( diminish_immutable ).toVar();
  26773. const lacunarity = float( lacunarity_immutable ).toVar();
  26774. const octaves = int( octaves_immutable ).toVar();
  26775. const p = vec3( p_immutable ).toVar();
  26776. 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 ) );
  26777. } ).setLayout( {
  26778. name: 'mx_fractal_noise_vec2',
  26779. type: 'vec2',
  26780. inputs: [
  26781. { name: 'p', type: 'vec3' },
  26782. { name: 'octaves', type: 'int' },
  26783. { name: 'lacunarity', type: 'float' },
  26784. { name: 'diminish', type: 'float' }
  26785. ]
  26786. } );
  26787. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  26788. const diminish = float( diminish_immutable ).toVar();
  26789. const lacunarity = float( lacunarity_immutable ).toVar();
  26790. const octaves = int( octaves_immutable ).toVar();
  26791. const p = vec3( p_immutable ).toVar();
  26792. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  26793. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  26794. return vec4( c, f );
  26795. } ).setLayout( {
  26796. name: 'mx_fractal_noise_vec4',
  26797. type: 'vec4',
  26798. inputs: [
  26799. { name: 'p', type: 'vec3' },
  26800. { name: 'octaves', type: 'int' },
  26801. { name: 'lacunarity', type: 'float' },
  26802. { name: 'diminish', type: 'float' }
  26803. ]
  26804. } );
  26805. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  26806. const metric = int( metric_immutable ).toVar();
  26807. const jitter = float( jitter_immutable ).toVar();
  26808. const yoff = int( yoff_immutable ).toVar();
  26809. const xoff = int( xoff_immutable ).toVar();
  26810. const y = int( y_immutable ).toVar();
  26811. const x = int( x_immutable ).toVar();
  26812. const p = vec2( p_immutable ).toVar();
  26813. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  26814. const off = vec2( tmp.x, tmp.y ).toVar();
  26815. off.subAssign( 0.5 );
  26816. off.mulAssign( jitter );
  26817. off.addAssign( 0.5 );
  26818. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  26819. const diff = vec2( cellpos.sub( p ) ).toVar();
  26820. If( metric.equal( int( 2 ) ), () => {
  26821. return abs( diff.x ).add( abs( diff.y ) );
  26822. } );
  26823. If( metric.equal( int( 3 ) ), () => {
  26824. return max$1( abs( diff.x ), abs( diff.y ) );
  26825. } );
  26826. return dot( diff, diff );
  26827. } ).setLayout( {
  26828. name: 'mx_worley_distance_0',
  26829. type: 'float',
  26830. inputs: [
  26831. { name: 'p', type: 'vec2' },
  26832. { name: 'x', type: 'int' },
  26833. { name: 'y', type: 'int' },
  26834. { name: 'xoff', type: 'int' },
  26835. { name: 'yoff', type: 'int' },
  26836. { name: 'jitter', type: 'float' },
  26837. { name: 'metric', type: 'int' }
  26838. ]
  26839. } );
  26840. 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 ] ) => {
  26841. const metric = int( metric_immutable ).toVar();
  26842. const jitter = float( jitter_immutable ).toVar();
  26843. const zoff = int( zoff_immutable ).toVar();
  26844. const yoff = int( yoff_immutable ).toVar();
  26845. const xoff = int( xoff_immutable ).toVar();
  26846. const z = int( z_immutable ).toVar();
  26847. const y = int( y_immutable ).toVar();
  26848. const x = int( x_immutable ).toVar();
  26849. const p = vec3( p_immutable ).toVar();
  26850. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  26851. off.subAssign( 0.5 );
  26852. off.mulAssign( jitter );
  26853. off.addAssign( 0.5 );
  26854. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  26855. const diff = vec3( cellpos.sub( p ) ).toVar();
  26856. If( metric.equal( int( 2 ) ), () => {
  26857. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  26858. } );
  26859. If( metric.equal( int( 3 ) ), () => {
  26860. return max$1( max$1( abs( diff.x ), abs( diff.y ) ), abs( diff.z ) );
  26861. } );
  26862. return dot( diff, diff );
  26863. } ).setLayout( {
  26864. name: 'mx_worley_distance_1',
  26865. type: 'float',
  26866. inputs: [
  26867. { name: 'p', type: 'vec3' },
  26868. { name: 'x', type: 'int' },
  26869. { name: 'y', type: 'int' },
  26870. { name: 'z', type: 'int' },
  26871. { name: 'xoff', type: 'int' },
  26872. { name: 'yoff', type: 'int' },
  26873. { name: 'zoff', type: 'int' },
  26874. { name: 'jitter', type: 'float' },
  26875. { name: 'metric', type: 'int' }
  26876. ]
  26877. } );
  26878. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  26879. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26880. const metric = int( metric_immutable ).toVar();
  26881. const jitter = float( jitter_immutable ).toVar();
  26882. const p = vec2( p_immutable ).toVar();
  26883. const X = int().toVar(), Y = int().toVar();
  26884. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26885. const sqdist = float( 1e6 ).toVar();
  26886. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26887. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26888. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26889. sqdist.assign( min$1( sqdist, dist ) );
  26890. } );
  26891. } );
  26892. If( metric.equal( int( 0 ) ), () => {
  26893. sqdist.assign( sqrt( sqdist ) );
  26894. } );
  26895. return sqdist;
  26896. } ).setLayout( {
  26897. name: 'mx_worley_noise_float_0',
  26898. type: 'float',
  26899. inputs: [
  26900. { name: 'p', type: 'vec2' },
  26901. { name: 'jitter', type: 'float' },
  26902. { name: 'metric', type: 'int' }
  26903. ]
  26904. } );
  26905. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26906. const metric = int( metric_immutable ).toVar();
  26907. const jitter = float( jitter_immutable ).toVar();
  26908. const p = vec2( p_immutable ).toVar();
  26909. const X = int().toVar(), Y = int().toVar();
  26910. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26911. const sqdist = vec2( 1e6, 1e6 ).toVar();
  26912. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26913. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26914. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26915. If( dist.lessThan( sqdist.x ), () => {
  26916. sqdist.y.assign( sqdist.x );
  26917. sqdist.x.assign( dist );
  26918. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26919. sqdist.y.assign( dist );
  26920. } );
  26921. } );
  26922. } );
  26923. If( metric.equal( int( 0 ) ), () => {
  26924. sqdist.assign( sqrt( sqdist ) );
  26925. } );
  26926. return sqdist;
  26927. } ).setLayout( {
  26928. name: 'mx_worley_noise_vec2_0',
  26929. type: 'vec2',
  26930. inputs: [
  26931. { name: 'p', type: 'vec2' },
  26932. { name: 'jitter', type: 'float' },
  26933. { name: 'metric', type: 'int' }
  26934. ]
  26935. } );
  26936. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26937. const metric = int( metric_immutable ).toVar();
  26938. const jitter = float( jitter_immutable ).toVar();
  26939. const p = vec2( p_immutable ).toVar();
  26940. const X = int().toVar(), Y = int().toVar();
  26941. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  26942. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  26943. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26944. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26945. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  26946. If( dist.lessThan( sqdist.x ), () => {
  26947. sqdist.z.assign( sqdist.y );
  26948. sqdist.y.assign( sqdist.x );
  26949. sqdist.x.assign( dist );
  26950. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  26951. sqdist.z.assign( sqdist.y );
  26952. sqdist.y.assign( dist );
  26953. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  26954. sqdist.z.assign( dist );
  26955. } );
  26956. } );
  26957. } );
  26958. If( metric.equal( int( 0 ) ), () => {
  26959. sqdist.assign( sqrt( sqdist ) );
  26960. } );
  26961. return sqdist;
  26962. } ).setLayout( {
  26963. name: 'mx_worley_noise_vec3_0',
  26964. type: 'vec3',
  26965. inputs: [
  26966. { name: 'p', type: 'vec2' },
  26967. { name: 'jitter', type: 'float' },
  26968. { name: 'metric', type: 'int' }
  26969. ]
  26970. } );
  26971. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  26972. const metric = int( metric_immutable ).toVar();
  26973. const jitter = float( jitter_immutable ).toVar();
  26974. const p = vec3( p_immutable ).toVar();
  26975. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  26976. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  26977. const sqdist = float( 1e6 ).toVar();
  26978. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  26979. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  26980. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  26981. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  26982. sqdist.assign( min$1( sqdist, dist ) );
  26983. } );
  26984. } );
  26985. } );
  26986. If( metric.equal( int( 0 ) ), () => {
  26987. sqdist.assign( sqrt( sqdist ) );
  26988. } );
  26989. return sqdist;
  26990. } ).setLayout( {
  26991. name: 'mx_worley_noise_float_1',
  26992. type: 'float',
  26993. inputs: [
  26994. { name: 'p', type: 'vec3' },
  26995. { name: 'jitter', type: 'float' },
  26996. { name: 'metric', type: 'int' }
  26997. ]
  26998. } );
  26999. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  27000. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27001. const metric = int( metric_immutable ).toVar();
  27002. const jitter = float( jitter_immutable ).toVar();
  27003. const p = vec3( p_immutable ).toVar();
  27004. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27005. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27006. const sqdist = vec2( 1e6, 1e6 ).toVar();
  27007. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27008. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27009. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27010. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27011. If( dist.lessThan( sqdist.x ), () => {
  27012. sqdist.y.assign( sqdist.x );
  27013. sqdist.x.assign( dist );
  27014. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27015. sqdist.y.assign( dist );
  27016. } );
  27017. } );
  27018. } );
  27019. } );
  27020. If( metric.equal( int( 0 ) ), () => {
  27021. sqdist.assign( sqrt( sqdist ) );
  27022. } );
  27023. return sqdist;
  27024. } ).setLayout( {
  27025. name: 'mx_worley_noise_vec2_1',
  27026. type: 'vec2',
  27027. inputs: [
  27028. { name: 'p', type: 'vec3' },
  27029. { name: 'jitter', type: 'float' },
  27030. { name: 'metric', type: 'int' }
  27031. ]
  27032. } );
  27033. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  27034. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  27035. const metric = int( metric_immutable ).toVar();
  27036. const jitter = float( jitter_immutable ).toVar();
  27037. const p = vec3( p_immutable ).toVar();
  27038. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  27039. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  27040. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  27041. Loop( { start: - 1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  27042. Loop( { start: - 1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  27043. Loop( { start: - 1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  27044. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  27045. If( dist.lessThan( sqdist.x ), () => {
  27046. sqdist.z.assign( sqdist.y );
  27047. sqdist.y.assign( sqdist.x );
  27048. sqdist.x.assign( dist );
  27049. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  27050. sqdist.z.assign( sqdist.y );
  27051. sqdist.y.assign( dist );
  27052. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  27053. sqdist.z.assign( dist );
  27054. } );
  27055. } );
  27056. } );
  27057. } );
  27058. If( metric.equal( int( 0 ) ), () => {
  27059. sqdist.assign( sqrt( sqdist ) );
  27060. } );
  27061. return sqdist;
  27062. } ).setLayout( {
  27063. name: 'mx_worley_noise_vec3_1',
  27064. type: 'vec3',
  27065. inputs: [
  27066. { name: 'p', type: 'vec3' },
  27067. { name: 'jitter', type: 'float' },
  27068. { name: 'metric', type: 'int' }
  27069. ]
  27070. } );
  27071. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  27072. // Three.js Transpiler
  27073. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  27074. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  27075. const s = hsv.y;
  27076. const v = hsv.z;
  27077. const result = vec3().toVar();
  27078. If( s.lessThan( 0.0001 ), () => {
  27079. result.assign( vec3( v, v, v ) );
  27080. } ).Else( () => {
  27081. let h = hsv.x;
  27082. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  27083. const hi = int( trunc( h ) );
  27084. const f = h.sub( float( hi ) );
  27085. const p = v.mul( s.oneMinus() );
  27086. const q = v.mul( s.mul( f ).oneMinus() );
  27087. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  27088. If( hi.equal( int( 0 ) ), () => {
  27089. result.assign( vec3( v, t, p ) );
  27090. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  27091. result.assign( vec3( q, v, p ) );
  27092. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  27093. result.assign( vec3( p, v, t ) );
  27094. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  27095. result.assign( vec3( p, q, v ) );
  27096. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  27097. result.assign( vec3( t, p, v ) );
  27098. } ).Else( () => {
  27099. result.assign( vec3( v, p, q ) );
  27100. } );
  27101. } );
  27102. return result;
  27103. } ).setLayout( {
  27104. name: 'mx_hsvtorgb',
  27105. type: 'vec3',
  27106. inputs: [
  27107. { name: 'hsv', type: 'vec3' }
  27108. ]
  27109. } );
  27110. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  27111. const c = vec3( c_immutable ).toVar();
  27112. const r = float( c.x ).toVar();
  27113. const g = float( c.y ).toVar();
  27114. const b = float( c.z ).toVar();
  27115. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  27116. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  27117. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  27118. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  27119. v.assign( maxcomp );
  27120. If( maxcomp.greaterThan( 0.0 ), () => {
  27121. s.assign( delta.div( maxcomp ) );
  27122. } ).Else( () => {
  27123. s.assign( 0.0 );
  27124. } );
  27125. If( s.lessThanEqual( 0.0 ), () => {
  27126. h.assign( 0.0 );
  27127. } ).Else( () => {
  27128. If( r.greaterThanEqual( maxcomp ), () => {
  27129. h.assign( g.sub( b ).div( delta ) );
  27130. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  27131. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  27132. } ).Else( () => {
  27133. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  27134. } );
  27135. h.mulAssign( 1.0 / 6.0 );
  27136. If( h.lessThan( 0.0 ), () => {
  27137. h.addAssign( 1.0 );
  27138. } );
  27139. } );
  27140. return vec3( h, s, v );
  27141. } ).setLayout( {
  27142. name: 'mx_rgbtohsv',
  27143. type: 'vec3',
  27144. inputs: [
  27145. { name: 'c', type: 'vec3' }
  27146. ]
  27147. } );
  27148. // Three.js Transpiler
  27149. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  27150. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  27151. const color = vec3( color_immutable ).toVar();
  27152. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  27153. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  27154. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  27155. return mix( linSeg, powSeg, isAbove );
  27156. } ).setLayout( {
  27157. name: 'mx_srgb_texture_to_lin_rec709',
  27158. type: 'vec3',
  27159. inputs: [
  27160. { name: 'color', type: 'vec3' }
  27161. ]
  27162. } );
  27163. const mx_aastep = ( threshold, value ) => {
  27164. threshold = float( threshold );
  27165. value = float( value );
  27166. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  27167. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  27168. };
  27169. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  27170. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  27171. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  27172. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  27173. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  27174. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  27175. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  27176. const mx_safepower = ( in1, in2 = 1 ) => {
  27177. in1 = float( in1 );
  27178. return in1.abs().pow( in2 ).mul( in1.sign() );
  27179. };
  27180. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  27181. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27182. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27183. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  27184. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  27185. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  27186. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  27187. return noise_vec4.mul( amplitude ).add( pivot );
  27188. };
  27189. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27190. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27191. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  27192. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  27193. 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 );
  27194. 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 );
  27195. 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 );
  27196. 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 );
  27197. /** @module getParallaxCorrectNormal **/
  27198. /**
  27199. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  27200. *
  27201. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  27202. *
  27203. * ```js
  27204. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  27205. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  27206. * ```
  27207. * @function
  27208. * @param {Node<vec3>} normal - The normal to correct.
  27209. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  27210. * @param {Node<vec3>} cubePos - The cube position.
  27211. * @return {Node<vec3>} The parallax corrected normal.
  27212. */
  27213. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  27214. const nDir = normalize( normal ).toVar( 'nDir' );
  27215. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmax' );
  27216. const rbmin = sub( float( - 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar( 'rbmin' );
  27217. const rbminmax = vec3().toVar( 'rbminmax' );
  27218. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  27219. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  27220. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  27221. const correction = min$1( min$1( rbminmax.x, rbminmax.y ), rbminmax.z ).toVar( 'correction' );
  27222. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar( 'boxIntersection' );
  27223. return boxIntersection.sub( cubePos );
  27224. } );
  27225. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  27226. // normal is assumed to have unit length
  27227. const x = normal.x, y = normal.y, z = normal.z;
  27228. // band 0
  27229. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  27230. // band 1
  27231. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  27232. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  27233. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  27234. // band 2
  27235. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  27236. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  27237. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  27238. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  27239. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  27240. return result;
  27241. } );
  27242. // constants
  27243. var TSL = /*#__PURE__*/Object.freeze({
  27244. __proto__: null,
  27245. BRDF_GGX: BRDF_GGX,
  27246. BRDF_Lambert: BRDF_Lambert,
  27247. BasicShadowFilter: BasicShadowFilter,
  27248. Break: Break,
  27249. Const: Const,
  27250. Continue: Continue,
  27251. DFGApprox: DFGApprox,
  27252. D_GGX: D_GGX,
  27253. Discard: Discard,
  27254. EPSILON: EPSILON,
  27255. F_Schlick: F_Schlick,
  27256. Fn: Fn,
  27257. INFINITY: INFINITY,
  27258. If: If,
  27259. Loop: Loop,
  27260. NodeAccess: NodeAccess,
  27261. NodeShaderStage: NodeShaderStage,
  27262. NodeType: NodeType,
  27263. NodeUpdateType: NodeUpdateType,
  27264. PCFShadowFilter: PCFShadowFilter,
  27265. PCFSoftShadowFilter: PCFSoftShadowFilter,
  27266. PI: PI,
  27267. PI2: PI2,
  27268. Return: Return,
  27269. Schlick_to_F0: Schlick_to_F0,
  27270. ScriptableNodeResources: ScriptableNodeResources,
  27271. ShaderNode: ShaderNode,
  27272. TBNViewMatrix: TBNViewMatrix,
  27273. VSMShadowFilter: VSMShadowFilter,
  27274. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  27275. Var: Var,
  27276. abs: abs,
  27277. acesFilmicToneMapping: acesFilmicToneMapping,
  27278. acos: acos,
  27279. add: add,
  27280. addMethodChaining: addMethodChaining,
  27281. addNodeElement: addNodeElement,
  27282. agxToneMapping: agxToneMapping,
  27283. all: all,
  27284. alphaT: alphaT,
  27285. and: and,
  27286. anisotropy: anisotropy,
  27287. anisotropyB: anisotropyB,
  27288. anisotropyT: anisotropyT,
  27289. any: any,
  27290. append: append,
  27291. arrayBuffer: arrayBuffer,
  27292. asin: asin,
  27293. assign: assign,
  27294. atan: atan,
  27295. atan2: atan2,
  27296. atomicAdd: atomicAdd,
  27297. atomicAnd: atomicAnd,
  27298. atomicFunc: atomicFunc,
  27299. atomicMax: atomicMax,
  27300. atomicMin: atomicMin,
  27301. atomicOr: atomicOr,
  27302. atomicStore: atomicStore,
  27303. atomicSub: atomicSub,
  27304. atomicXor: atomicXor,
  27305. attenuationColor: attenuationColor,
  27306. attenuationDistance: attenuationDistance,
  27307. attribute: attribute,
  27308. attributeArray: attributeArray,
  27309. backgroundBlurriness: backgroundBlurriness,
  27310. backgroundIntensity: backgroundIntensity,
  27311. backgroundRotation: backgroundRotation,
  27312. batch: batch,
  27313. billboarding: billboarding,
  27314. bitAnd: bitAnd,
  27315. bitNot: bitNot,
  27316. bitOr: bitOr,
  27317. bitXor: bitXor,
  27318. bitangentGeometry: bitangentGeometry,
  27319. bitangentLocal: bitangentLocal,
  27320. bitangentView: bitangentView,
  27321. bitangentWorld: bitangentWorld,
  27322. bitcast: bitcast,
  27323. blendBurn: blendBurn,
  27324. blendColor: blendColor,
  27325. blendDodge: blendDodge,
  27326. blendOverlay: blendOverlay,
  27327. blendScreen: blendScreen,
  27328. blur: blur,
  27329. bool: bool,
  27330. buffer: buffer,
  27331. bufferAttribute: bufferAttribute,
  27332. bumpMap: bumpMap,
  27333. burn: burn,
  27334. bvec2: bvec2,
  27335. bvec3: bvec3,
  27336. bvec4: bvec4,
  27337. bypass: bypass,
  27338. cache: cache,
  27339. call: call,
  27340. cameraFar: cameraFar,
  27341. cameraIndex: cameraIndex,
  27342. cameraNear: cameraNear,
  27343. cameraNormalMatrix: cameraNormalMatrix,
  27344. cameraPosition: cameraPosition,
  27345. cameraProjectionMatrix: cameraProjectionMatrix,
  27346. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  27347. cameraViewMatrix: cameraViewMatrix,
  27348. cameraWorldMatrix: cameraWorldMatrix,
  27349. cbrt: cbrt,
  27350. cdl: cdl,
  27351. ceil: ceil,
  27352. checker: checker,
  27353. cineonToneMapping: cineonToneMapping,
  27354. clamp: clamp,
  27355. clearcoat: clearcoat,
  27356. clearcoatRoughness: clearcoatRoughness,
  27357. code: code,
  27358. color: color,
  27359. colorSpaceToWorking: colorSpaceToWorking,
  27360. colorToDirection: colorToDirection,
  27361. compute: compute,
  27362. cond: cond,
  27363. context: context,
  27364. convert: convert,
  27365. convertColorSpace: convertColorSpace,
  27366. convertToTexture: convertToTexture,
  27367. cos: cos,
  27368. cross: cross,
  27369. cubeTexture: cubeTexture,
  27370. dFdx: dFdx,
  27371. dFdy: dFdy,
  27372. dashSize: dashSize,
  27373. defaultBuildStages: defaultBuildStages,
  27374. defaultShaderStages: defaultShaderStages,
  27375. defined: defined,
  27376. degrees: degrees,
  27377. deltaTime: deltaTime,
  27378. densityFog: densityFog,
  27379. densityFogFactor: densityFogFactor,
  27380. depth: depth,
  27381. depthPass: depthPass,
  27382. difference: difference,
  27383. diffuseColor: diffuseColor,
  27384. directPointLight: directPointLight,
  27385. directionToColor: directionToColor,
  27386. dispersion: dispersion,
  27387. distance: distance,
  27388. div: div,
  27389. dodge: dodge,
  27390. dot: dot,
  27391. drawIndex: drawIndex,
  27392. dynamicBufferAttribute: dynamicBufferAttribute,
  27393. element: element,
  27394. emissive: emissive,
  27395. equal: equal,
  27396. equals: equals,
  27397. equirectUV: equirectUV,
  27398. exp: exp,
  27399. exp2: exp2,
  27400. expression: expression,
  27401. faceDirection: faceDirection,
  27402. faceForward: faceForward,
  27403. faceforward: faceforward,
  27404. float: float,
  27405. floor: floor,
  27406. fog: fog,
  27407. fract: fract,
  27408. frameGroup: frameGroup,
  27409. frameId: frameId,
  27410. frontFacing: frontFacing,
  27411. fwidth: fwidth,
  27412. gain: gain,
  27413. gapSize: gapSize,
  27414. getConstNodeType: getConstNodeType,
  27415. getCurrentStack: getCurrentStack,
  27416. getDirection: getDirection,
  27417. getDistanceAttenuation: getDistanceAttenuation,
  27418. getGeometryRoughness: getGeometryRoughness,
  27419. getNormalFromDepth: getNormalFromDepth,
  27420. getParallaxCorrectNormal: getParallaxCorrectNormal,
  27421. getRoughness: getRoughness,
  27422. getScreenPosition: getScreenPosition,
  27423. getShIrradianceAt: getShIrradianceAt,
  27424. getTextureIndex: getTextureIndex,
  27425. getViewPosition: getViewPosition,
  27426. globalId: globalId,
  27427. glsl: glsl,
  27428. glslFn: glslFn,
  27429. grayscale: grayscale,
  27430. greaterThan: greaterThan,
  27431. greaterThanEqual: greaterThanEqual,
  27432. hash: hash,
  27433. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  27434. highpModelViewMatrix: highpModelViewMatrix,
  27435. hue: hue,
  27436. instance: instance,
  27437. instanceIndex: instanceIndex,
  27438. instancedArray: instancedArray,
  27439. instancedBufferAttribute: instancedBufferAttribute,
  27440. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  27441. instancedMesh: instancedMesh,
  27442. int: int,
  27443. inverseSqrt: inverseSqrt,
  27444. inversesqrt: inversesqrt,
  27445. invocationLocalIndex: invocationLocalIndex,
  27446. invocationSubgroupIndex: invocationSubgroupIndex,
  27447. ior: ior,
  27448. iridescence: iridescence,
  27449. iridescenceIOR: iridescenceIOR,
  27450. iridescenceThickness: iridescenceThickness,
  27451. ivec2: ivec2,
  27452. ivec3: ivec3,
  27453. ivec4: ivec4,
  27454. js: js,
  27455. label: label,
  27456. length: length,
  27457. lengthSq: lengthSq,
  27458. lessThan: lessThan,
  27459. lessThanEqual: lessThanEqual,
  27460. lightPosition: lightPosition,
  27461. lightProjectionUV: lightProjectionUV,
  27462. lightShadowMatrix: lightShadowMatrix,
  27463. lightTargetDirection: lightTargetDirection,
  27464. lightTargetPosition: lightTargetPosition,
  27465. lightViewPosition: lightViewPosition,
  27466. lightingContext: lightingContext,
  27467. lights: lights,
  27468. linearDepth: linearDepth,
  27469. linearToneMapping: linearToneMapping,
  27470. localId: localId,
  27471. log: log,
  27472. log2: log2,
  27473. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  27474. loop: loop,
  27475. luminance: luminance,
  27476. mat2: mat2,
  27477. mat3: mat3,
  27478. mat4: mat4,
  27479. matcapUV: matcapUV,
  27480. materialAO: materialAO,
  27481. materialAlphaTest: materialAlphaTest,
  27482. materialAnisotropy: materialAnisotropy,
  27483. materialAnisotropyVector: materialAnisotropyVector,
  27484. materialAttenuationColor: materialAttenuationColor,
  27485. materialAttenuationDistance: materialAttenuationDistance,
  27486. materialClearcoat: materialClearcoat,
  27487. materialClearcoatNormal: materialClearcoatNormal,
  27488. materialClearcoatRoughness: materialClearcoatRoughness,
  27489. materialColor: materialColor,
  27490. materialDispersion: materialDispersion,
  27491. materialEmissive: materialEmissive,
  27492. materialIOR: materialIOR,
  27493. materialIridescence: materialIridescence,
  27494. materialIridescenceIOR: materialIridescenceIOR,
  27495. materialIridescenceThickness: materialIridescenceThickness,
  27496. materialLightMap: materialLightMap,
  27497. materialLineDashOffset: materialLineDashOffset,
  27498. materialLineDashSize: materialLineDashSize,
  27499. materialLineGapSize: materialLineGapSize,
  27500. materialLineScale: materialLineScale,
  27501. materialLineWidth: materialLineWidth,
  27502. materialMetalness: materialMetalness,
  27503. materialNormal: materialNormal,
  27504. materialOpacity: materialOpacity,
  27505. materialPointSize: materialPointSize,
  27506. materialReference: materialReference,
  27507. materialReflectivity: materialReflectivity,
  27508. materialRefractionRatio: materialRefractionRatio,
  27509. materialRotation: materialRotation,
  27510. materialRoughness: materialRoughness,
  27511. materialSheen: materialSheen,
  27512. materialSheenRoughness: materialSheenRoughness,
  27513. materialShininess: materialShininess,
  27514. materialSpecular: materialSpecular,
  27515. materialSpecularColor: materialSpecularColor,
  27516. materialSpecularIntensity: materialSpecularIntensity,
  27517. materialSpecularStrength: materialSpecularStrength,
  27518. materialThickness: materialThickness,
  27519. materialTransmission: materialTransmission,
  27520. max: max$1,
  27521. maxMipLevel: maxMipLevel,
  27522. mediumpModelViewMatrix: mediumpModelViewMatrix,
  27523. metalness: metalness,
  27524. min: min$1,
  27525. mix: mix,
  27526. mixElement: mixElement,
  27527. mod: mod,
  27528. modInt: modInt,
  27529. modelDirection: modelDirection,
  27530. modelNormalMatrix: modelNormalMatrix,
  27531. modelPosition: modelPosition,
  27532. modelScale: modelScale,
  27533. modelViewMatrix: modelViewMatrix,
  27534. modelViewPosition: modelViewPosition,
  27535. modelViewProjection: modelViewProjection,
  27536. modelWorldMatrix: modelWorldMatrix,
  27537. modelWorldMatrixInverse: modelWorldMatrixInverse,
  27538. morphReference: morphReference,
  27539. mrt: mrt,
  27540. mul: mul,
  27541. mx_aastep: mx_aastep,
  27542. mx_cell_noise_float: mx_cell_noise_float,
  27543. mx_contrast: mx_contrast,
  27544. mx_fractal_noise_float: mx_fractal_noise_float,
  27545. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  27546. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  27547. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  27548. mx_hsvtorgb: mx_hsvtorgb,
  27549. mx_noise_float: mx_noise_float,
  27550. mx_noise_vec3: mx_noise_vec3,
  27551. mx_noise_vec4: mx_noise_vec4,
  27552. mx_ramplr: mx_ramplr,
  27553. mx_ramptb: mx_ramptb,
  27554. mx_rgbtohsv: mx_rgbtohsv,
  27555. mx_safepower: mx_safepower,
  27556. mx_splitlr: mx_splitlr,
  27557. mx_splittb: mx_splittb,
  27558. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  27559. mx_transform_uv: mx_transform_uv,
  27560. mx_worley_noise_float: mx_worley_noise_float,
  27561. mx_worley_noise_vec2: mx_worley_noise_vec2,
  27562. mx_worley_noise_vec3: mx_worley_noise_vec3,
  27563. negate: negate,
  27564. neutralToneMapping: neutralToneMapping,
  27565. nodeArray: nodeArray,
  27566. nodeImmutable: nodeImmutable,
  27567. nodeObject: nodeObject,
  27568. nodeObjects: nodeObjects,
  27569. nodeProxy: nodeProxy,
  27570. normalFlat: normalFlat,
  27571. normalGeometry: normalGeometry,
  27572. normalLocal: normalLocal,
  27573. normalMap: normalMap,
  27574. normalView: normalView,
  27575. normalWorld: normalWorld,
  27576. normalize: normalize,
  27577. not: not,
  27578. notEqual: notEqual,
  27579. numWorkgroups: numWorkgroups,
  27580. objectDirection: objectDirection,
  27581. objectGroup: objectGroup,
  27582. objectPosition: objectPosition,
  27583. objectScale: objectScale,
  27584. objectViewPosition: objectViewPosition,
  27585. objectWorldMatrix: objectWorldMatrix,
  27586. oneMinus: oneMinus,
  27587. or: or,
  27588. orthographicDepthToViewZ: orthographicDepthToViewZ,
  27589. oscSawtooth: oscSawtooth,
  27590. oscSine: oscSine,
  27591. oscSquare: oscSquare,
  27592. oscTriangle: oscTriangle,
  27593. output: output,
  27594. outputStruct: outputStruct,
  27595. overlay: overlay,
  27596. overloadingFn: overloadingFn,
  27597. parabola: parabola,
  27598. parallaxDirection: parallaxDirection,
  27599. parallaxUV: parallaxUV,
  27600. parameter: parameter,
  27601. pass: pass,
  27602. passTexture: passTexture,
  27603. pcurve: pcurve,
  27604. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  27605. pmremTexture: pmremTexture,
  27606. pointUV: pointUV,
  27607. pointWidth: pointWidth,
  27608. positionGeometry: positionGeometry,
  27609. positionLocal: positionLocal,
  27610. positionPrevious: positionPrevious,
  27611. positionView: positionView,
  27612. positionViewDirection: positionViewDirection,
  27613. positionWorld: positionWorld,
  27614. positionWorldDirection: positionWorldDirection,
  27615. posterize: posterize,
  27616. pow: pow,
  27617. pow2: pow2,
  27618. pow3: pow3,
  27619. pow4: pow4,
  27620. property: property,
  27621. radians: radians,
  27622. rand: rand,
  27623. range: range,
  27624. rangeFog: rangeFog,
  27625. rangeFogFactor: rangeFogFactor,
  27626. reciprocal: reciprocal,
  27627. reference: reference,
  27628. referenceBuffer: referenceBuffer,
  27629. reflect: reflect,
  27630. reflectVector: reflectVector,
  27631. reflectView: reflectView,
  27632. reflector: reflector,
  27633. refract: refract,
  27634. refractVector: refractVector,
  27635. refractView: refractView,
  27636. reinhardToneMapping: reinhardToneMapping,
  27637. remainder: remainder,
  27638. remap: remap,
  27639. remapClamp: remapClamp,
  27640. renderGroup: renderGroup,
  27641. renderOutput: renderOutput,
  27642. rendererReference: rendererReference,
  27643. rotate: rotate,
  27644. rotateUV: rotateUV,
  27645. roughness: roughness,
  27646. round: round,
  27647. rtt: rtt,
  27648. sRGBTransferEOTF: sRGBTransferEOTF,
  27649. sRGBTransferOETF: sRGBTransferOETF,
  27650. sampler: sampler,
  27651. saturate: saturate,
  27652. saturation: saturation,
  27653. screen: screen,
  27654. screenCoordinate: screenCoordinate,
  27655. screenSize: screenSize,
  27656. screenUV: screenUV,
  27657. scriptable: scriptable,
  27658. scriptableValue: scriptableValue,
  27659. select: select,
  27660. setCurrentStack: setCurrentStack,
  27661. shaderStages: shaderStages,
  27662. shadow: shadow,
  27663. shadowPositionWorld: shadowPositionWorld,
  27664. shapeCircle: shapeCircle,
  27665. sharedUniformGroup: sharedUniformGroup,
  27666. sheen: sheen,
  27667. sheenRoughness: sheenRoughness,
  27668. shiftLeft: shiftLeft,
  27669. shiftRight: shiftRight,
  27670. shininess: shininess,
  27671. sign: sign,
  27672. sin: sin,
  27673. sinc: sinc,
  27674. skinning: skinning,
  27675. skinningReference: skinningReference,
  27676. smoothstep: smoothstep,
  27677. smoothstepElement: smoothstepElement,
  27678. specularColor: specularColor,
  27679. specularF90: specularF90,
  27680. spherizeUV: spherizeUV,
  27681. split: split,
  27682. spritesheetUV: spritesheetUV,
  27683. sqrt: sqrt,
  27684. stack: stack,
  27685. step: step,
  27686. storage: storage,
  27687. storageBarrier: storageBarrier,
  27688. storageObject: storageObject,
  27689. storageTexture: storageTexture,
  27690. string: string,
  27691. sub: sub,
  27692. subgroupIndex: subgroupIndex,
  27693. subgroupSize: subgroupSize,
  27694. tan: tan,
  27695. tangentGeometry: tangentGeometry,
  27696. tangentLocal: tangentLocal,
  27697. tangentView: tangentView,
  27698. tangentWorld: tangentWorld,
  27699. temp: temp,
  27700. texture: texture,
  27701. texture3D: texture3D,
  27702. textureBarrier: textureBarrier,
  27703. textureBicubic: textureBicubic,
  27704. textureCubeUV: textureCubeUV,
  27705. textureLoad: textureLoad,
  27706. textureSize: textureSize,
  27707. textureStore: textureStore,
  27708. thickness: thickness,
  27709. time: time,
  27710. timerDelta: timerDelta,
  27711. timerGlobal: timerGlobal,
  27712. timerLocal: timerLocal,
  27713. toOutputColorSpace: toOutputColorSpace,
  27714. toWorkingColorSpace: toWorkingColorSpace,
  27715. toneMapping: toneMapping,
  27716. toneMappingExposure: toneMappingExposure,
  27717. toonOutlinePass: toonOutlinePass,
  27718. transformDirection: transformDirection,
  27719. transformNormal: transformNormal,
  27720. transformNormalToView: transformNormalToView,
  27721. transformedBentNormalView: transformedBentNormalView,
  27722. transformedBitangentView: transformedBitangentView,
  27723. transformedBitangentWorld: transformedBitangentWorld,
  27724. transformedClearcoatNormalView: transformedClearcoatNormalView,
  27725. transformedNormalView: transformedNormalView,
  27726. transformedNormalWorld: transformedNormalWorld,
  27727. transformedTangentView: transformedTangentView,
  27728. transformedTangentWorld: transformedTangentWorld,
  27729. transmission: transmission,
  27730. transpose: transpose,
  27731. triNoise3D: triNoise3D,
  27732. triplanarTexture: triplanarTexture,
  27733. triplanarTextures: triplanarTextures,
  27734. trunc: trunc,
  27735. tslFn: tslFn,
  27736. uint: uint,
  27737. uniform: uniform,
  27738. uniformArray: uniformArray,
  27739. uniformGroup: uniformGroup,
  27740. uniforms: uniforms,
  27741. userData: userData,
  27742. uv: uv,
  27743. uvec2: uvec2,
  27744. uvec3: uvec3,
  27745. uvec4: uvec4,
  27746. varying: varying,
  27747. varyingProperty: varyingProperty,
  27748. vec2: vec2,
  27749. vec3: vec3,
  27750. vec4: vec4,
  27751. vectorComponents: vectorComponents,
  27752. velocity: velocity,
  27753. vertexColor: vertexColor,
  27754. vertexIndex: vertexIndex,
  27755. vertexStage: vertexStage,
  27756. vibrance: vibrance,
  27757. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  27758. viewZToOrthographicDepth: viewZToOrthographicDepth,
  27759. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  27760. viewport: viewport,
  27761. viewportBottomLeft: viewportBottomLeft,
  27762. viewportCoordinate: viewportCoordinate,
  27763. viewportDepthTexture: viewportDepthTexture,
  27764. viewportLinearDepth: viewportLinearDepth,
  27765. viewportMipTexture: viewportMipTexture,
  27766. viewportResolution: viewportResolution,
  27767. viewportSafeUV: viewportSafeUV,
  27768. viewportSharedTexture: viewportSharedTexture,
  27769. viewportSize: viewportSize,
  27770. viewportTexture: viewportTexture,
  27771. viewportTopLeft: viewportTopLeft,
  27772. viewportUV: viewportUV,
  27773. wgsl: wgsl,
  27774. wgslFn: wgslFn,
  27775. workgroupArray: workgroupArray,
  27776. workgroupBarrier: workgroupBarrier,
  27777. workgroupId: workgroupId,
  27778. workingToColorSpace: workingToColorSpace,
  27779. xor: xor
  27780. });
  27781. const _clearColor$1 = /*@__PURE__*/ new Color4();
  27782. /**
  27783. * This renderer module manages the background.
  27784. *
  27785. * @private
  27786. * @augments DataMap
  27787. */
  27788. class Background extends DataMap {
  27789. /**
  27790. * Constructs a new background management component.
  27791. *
  27792. * @param {Renderer} renderer - The renderer.
  27793. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  27794. */
  27795. constructor( renderer, nodes ) {
  27796. super();
  27797. /**
  27798. * The renderer.
  27799. *
  27800. * @type {Renderer}
  27801. */
  27802. this.renderer = renderer;
  27803. /**
  27804. * Renderer component for managing nodes related logic.
  27805. *
  27806. * @type {Nodes}
  27807. */
  27808. this.nodes = nodes;
  27809. }
  27810. /**
  27811. * Updates the background for the given scene. Depending on how `Scene.background`
  27812. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  27813. * or add a mesh to the render list for rendering the background as a textured plane
  27814. * or skybox.
  27815. *
  27816. * @param {Scene} scene - The scene.
  27817. * @param {RenderList} renderList - The current render list.
  27818. * @param {RenderContext} renderContext - The current render context.
  27819. */
  27820. update( scene, renderList, renderContext ) {
  27821. const renderer = this.renderer;
  27822. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  27823. let forceClear = false;
  27824. if ( background === null ) {
  27825. // no background settings, use clear color configuration from the renderer
  27826. renderer._clearColor.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27827. _clearColor$1.a = renderer._clearColor.a;
  27828. } else if ( background.isColor === true ) {
  27829. // background is an opaque color
  27830. background.getRGB( _clearColor$1, LinearSRGBColorSpace );
  27831. _clearColor$1.a = 1;
  27832. forceClear = true;
  27833. } else if ( background.isNode === true ) {
  27834. const sceneData = this.get( scene );
  27835. const backgroundNode = background;
  27836. _clearColor$1.copy( renderer._clearColor );
  27837. let backgroundMesh = sceneData.backgroundMesh;
  27838. if ( backgroundMesh === undefined ) {
  27839. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  27840. // @TODO: Add Texture2D support using node context
  27841. getUV: () => backgroundRotation.mul( normalWorld ),
  27842. getTextureLevel: () => backgroundBlurriness
  27843. } );
  27844. let viewProj = modelViewProjection;
  27845. viewProj = viewProj.setZ( viewProj.w );
  27846. const nodeMaterial = new NodeMaterial();
  27847. nodeMaterial.name = 'Background.material';
  27848. nodeMaterial.side = BackSide;
  27849. nodeMaterial.depthTest = false;
  27850. nodeMaterial.depthWrite = false;
  27851. nodeMaterial.fog = false;
  27852. nodeMaterial.lights = false;
  27853. nodeMaterial.vertexNode = viewProj;
  27854. nodeMaterial.colorNode = backgroundMeshNode;
  27855. sceneData.backgroundMeshNode = backgroundMeshNode;
  27856. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  27857. backgroundMesh.frustumCulled = false;
  27858. backgroundMesh.name = 'Background.mesh';
  27859. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  27860. this.matrixWorld.copyPosition( camera.matrixWorld );
  27861. };
  27862. }
  27863. const backgroundCacheKey = backgroundNode.getCacheKey();
  27864. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  27865. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  27866. sceneData.backgroundMeshNode.needsUpdate = true;
  27867. backgroundMesh.material.needsUpdate = true;
  27868. sceneData.backgroundCacheKey = backgroundCacheKey;
  27869. }
  27870. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  27871. } else {
  27872. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  27873. }
  27874. //
  27875. if ( renderer.autoClear === true || forceClear === true ) {
  27876. const clearColorValue = renderContext.clearColorValue;
  27877. clearColorValue.r = _clearColor$1.r;
  27878. clearColorValue.g = _clearColor$1.g;
  27879. clearColorValue.b = _clearColor$1.b;
  27880. clearColorValue.a = _clearColor$1.a;
  27881. // premultiply alpha
  27882. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  27883. clearColorValue.r *= clearColorValue.a;
  27884. clearColorValue.g *= clearColorValue.a;
  27885. clearColorValue.b *= clearColorValue.a;
  27886. }
  27887. //
  27888. renderContext.depthClearValue = renderer._clearDepth;
  27889. renderContext.stencilClearValue = renderer._clearStencil;
  27890. renderContext.clearColor = renderer.autoClearColor === true;
  27891. renderContext.clearDepth = renderer.autoClearDepth === true;
  27892. renderContext.clearStencil = renderer.autoClearStencil === true;
  27893. } else {
  27894. renderContext.clearColor = false;
  27895. renderContext.clearDepth = false;
  27896. renderContext.clearStencil = false;
  27897. }
  27898. }
  27899. }
  27900. let _id$6 = 0;
  27901. /**
  27902. * A bind group represents a collection of bindings and thus a collection
  27903. * or resources. Bind groups are assigned to pipelines to provide them
  27904. * with the required resources (like uniform buffers or textures).
  27905. *
  27906. * @private
  27907. */
  27908. class BindGroup {
  27909. /**
  27910. * Constructs a new bind group.
  27911. *
  27912. * @param {String} name - The bind group's name.
  27913. * @param {Array<Binding>} bindings - An array of bindings.
  27914. * @param {Number} index - The group index.
  27915. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  27916. */
  27917. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  27918. /**
  27919. * The bind group's name.
  27920. *
  27921. * @type {String}
  27922. */
  27923. this.name = name;
  27924. /**
  27925. * An array of bindings.
  27926. *
  27927. * @type {Array<Binding>}
  27928. */
  27929. this.bindings = bindings;
  27930. /**
  27931. * The group index.
  27932. *
  27933. * @type {Number}
  27934. */
  27935. this.index = index;
  27936. /**
  27937. * An array of reference bindings.
  27938. *
  27939. * @type {Array<Binding>}
  27940. */
  27941. this.bindingsReference = bindingsReference;
  27942. /**
  27943. * The group's ID.
  27944. *
  27945. * @type {Number}
  27946. */
  27947. this.id = _id$6 ++;
  27948. }
  27949. }
  27950. /**
  27951. * This module represents the state of a node builder after it was
  27952. * used to build the nodes for a render object. The state holds the
  27953. * results of the build for further processing in the renderer.
  27954. *
  27955. * Render objects with identical cache keys share the same node builder state.
  27956. *
  27957. * @private
  27958. */
  27959. class NodeBuilderState {
  27960. /**
  27961. * Constructs a new node builder state.
  27962. *
  27963. * @param {String?} vertexShader - The native vertex shader code.
  27964. * @param {String?} fragmentShader - The native fragment shader code.
  27965. * @param {String?} computeShader - The native compute shader code.
  27966. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  27967. * @param {Array<BindGroup>} bindings - An array of bind groups.
  27968. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  27969. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  27970. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  27971. * @param {NodeMaterialObserver} monitor - A node material observer.
  27972. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  27973. */
  27974. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, monitor, transforms = [] ) {
  27975. /**
  27976. * The native vertex shader code.
  27977. *
  27978. * @type {String}
  27979. */
  27980. this.vertexShader = vertexShader;
  27981. /**
  27982. * The native fragment shader code.
  27983. *
  27984. * @type {String}
  27985. */
  27986. this.fragmentShader = fragmentShader;
  27987. /**
  27988. * The native compute shader code.
  27989. *
  27990. * @type {String}
  27991. */
  27992. this.computeShader = computeShader;
  27993. /**
  27994. * An array with transform attribute objects.
  27995. * Only relevant when using compute shaders with WebGL 2.
  27996. *
  27997. * @type {Array<Object>}
  27998. */
  27999. this.transforms = transforms;
  28000. /**
  28001. * An array of node attributes representing
  28002. * the attributes of the shaders.
  28003. *
  28004. * @type {Array<NodeAttribute>}
  28005. */
  28006. this.nodeAttributes = nodeAttributes;
  28007. /**
  28008. * An array of bind groups representing the uniform or storage
  28009. * buffers, texture or samplers of the shader.
  28010. *
  28011. * @type {Array<BindGroup>}
  28012. */
  28013. this.bindings = bindings;
  28014. /**
  28015. * An array of nodes that implement their `update()` method.
  28016. *
  28017. * @type {Array<Node>}
  28018. */
  28019. this.updateNodes = updateNodes;
  28020. /**
  28021. * An array of nodes that implement their `updateBefore()` method.
  28022. *
  28023. * @type {Array<Node>}
  28024. */
  28025. this.updateBeforeNodes = updateBeforeNodes;
  28026. /**
  28027. * An array of nodes that implement their `updateAfter()` method.
  28028. *
  28029. * @type {Array<Node>}
  28030. */
  28031. this.updateAfterNodes = updateAfterNodes;
  28032. /**
  28033. * A node material observer.
  28034. *
  28035. * @type {NodeMaterialObserver}
  28036. */
  28037. this.monitor = monitor;
  28038. /**
  28039. * How often this state is used by render objects.
  28040. *
  28041. * @type {Number}
  28042. */
  28043. this.usedTimes = 0;
  28044. }
  28045. /**
  28046. * This method is used to create a array of bind groups based
  28047. * on the existing bind groups of this state. Shared groups are
  28048. * not cloned.
  28049. *
  28050. * @return {Array<BindGroup>} A array of bind groups.
  28051. */
  28052. createBindings() {
  28053. const bindings = [];
  28054. for ( const instanceGroup of this.bindings ) {
  28055. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // TODO: Is it safe to always check the first binding in the group?
  28056. if ( shared !== true ) {
  28057. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  28058. bindings.push( bindingsGroup );
  28059. for ( const instanceBinding of instanceGroup.bindings ) {
  28060. bindingsGroup.bindings.push( instanceBinding.clone() );
  28061. }
  28062. } else {
  28063. bindings.push( instanceGroup );
  28064. }
  28065. }
  28066. return bindings;
  28067. }
  28068. }
  28069. /**
  28070. * {@link NodeBuilder} is going to create instances of this class during the build process
  28071. * of nodes. They represent the final shader attributes that are going to be generated
  28072. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  28073. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  28074. */
  28075. class NodeAttribute {
  28076. /**
  28077. * Constructs a new node attribute.
  28078. *
  28079. * @param {String} name - The name of the attribute.
  28080. * @param {String} type - The type of the attribute.
  28081. * @param {Node?} node - An optional reference to the node.
  28082. */
  28083. constructor( name, type, node = null ) {
  28084. /**
  28085. * This flag can be used for type testing.
  28086. *
  28087. * @type {Boolean}
  28088. * @readonly
  28089. * @default true
  28090. */
  28091. this.isNodeAttribute = true;
  28092. /**
  28093. * The name of the attribute.
  28094. *
  28095. * @type {String}
  28096. */
  28097. this.name = name;
  28098. /**
  28099. * The type of the attribute.
  28100. *
  28101. * @type {String}
  28102. */
  28103. this.type = type;
  28104. /**
  28105. * An optional reference to the node.
  28106. *
  28107. * @type {Node?}
  28108. * @default null
  28109. */
  28110. this.node = node;
  28111. }
  28112. }
  28113. /**
  28114. * {@link NodeBuilder} is going to create instances of this class during the build process
  28115. * of nodes. They represent the final shader uniforms that are going to be generated
  28116. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  28117. * for this purpose.
  28118. */
  28119. class NodeUniform {
  28120. /**
  28121. * Constructs a new node uniform.
  28122. *
  28123. * @param {String} name - The name of the uniform.
  28124. * @param {String} type - The type of the uniform.
  28125. * @param {UniformNode} node - An reference to the node.
  28126. */
  28127. constructor( name, type, node ) {
  28128. /**
  28129. * This flag can be used for type testing.
  28130. *
  28131. * @type {Boolean}
  28132. * @readonly
  28133. * @default true
  28134. */
  28135. this.isNodeUniform = true;
  28136. /**
  28137. * The name of the uniform.
  28138. *
  28139. * @type {String}
  28140. */
  28141. this.name = name;
  28142. /**
  28143. * The type of the uniform.
  28144. *
  28145. * @type {String}
  28146. */
  28147. this.type = type;
  28148. /**
  28149. * An reference to the node.
  28150. *
  28151. * @type {UniformNode}
  28152. */
  28153. this.node = node.getSelf();
  28154. }
  28155. /**
  28156. * The value of the uniform node.
  28157. *
  28158. * @type {Any}
  28159. */
  28160. get value() {
  28161. return this.node.value;
  28162. }
  28163. set value( val ) {
  28164. this.node.value = val;
  28165. }
  28166. /**
  28167. * The id of the uniform node.
  28168. *
  28169. * @type {Number}
  28170. */
  28171. get id() {
  28172. return this.node.id;
  28173. }
  28174. /**
  28175. * The uniform node's group.
  28176. *
  28177. * @type {UniformGroupNode}
  28178. */
  28179. get groupNode() {
  28180. return this.node.groupNode;
  28181. }
  28182. }
  28183. /**
  28184. * {@link NodeBuilder} is going to create instances of this class during the build process
  28185. * of nodes. They represent the final shader variables that are going to be generated
  28186. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  28187. * this purpose.
  28188. */
  28189. class NodeVar {
  28190. /**
  28191. * Constructs a new node variable.
  28192. *
  28193. * @param {String} name - The name of the variable.
  28194. * @param {String} type - The type of the variable.
  28195. * @param {Boolean} [readOnly=false] - The read-only flag.
  28196. */
  28197. constructor( name, type, readOnly = false ) {
  28198. /**
  28199. * This flag can be used for type testing.
  28200. *
  28201. * @type {Boolean}
  28202. * @readonly
  28203. * @default true
  28204. */
  28205. this.isNodeVar = true;
  28206. /**
  28207. * The name of the variable.
  28208. *
  28209. * @type {String}
  28210. */
  28211. this.name = name;
  28212. /**
  28213. * The type of the variable.
  28214. *
  28215. * @type {String}
  28216. */
  28217. this.type = type;
  28218. /**
  28219. * The read-only flag.
  28220. *
  28221. * @type {boolean}
  28222. */
  28223. this.readOnly = readOnly;
  28224. }
  28225. }
  28226. /**
  28227. * {@link NodeBuilder} is going to create instances of this class during the build process
  28228. * of nodes. They represent the final shader varyings that are going to be generated
  28229. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  28230. * this purpose.
  28231. *
  28232. * @augments NodeVar
  28233. */
  28234. class NodeVarying extends NodeVar {
  28235. /**
  28236. * Constructs a new node varying.
  28237. *
  28238. * @param {String} name - The name of the varying.
  28239. * @param {String} type - The type of the varying.
  28240. */
  28241. constructor( name, type ) {
  28242. super( name, type );
  28243. /**
  28244. * Whether this varying requires interpolation or not. This property can be used
  28245. * to check if the varying can be optimized for a variable.
  28246. *
  28247. * @type {Boolean}
  28248. * @default false
  28249. */
  28250. this.needsInterpolation = false;
  28251. /**
  28252. * This flag can be used for type testing.
  28253. *
  28254. * @type {Boolean}
  28255. * @readonly
  28256. * @default true
  28257. */
  28258. this.isNodeVarying = true;
  28259. }
  28260. }
  28261. /**
  28262. * {@link NodeBuilder} is going to create instances of this class during the build process
  28263. * of nodes. They represent user-defined, native shader code portions that are going to be
  28264. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  28265. * for this purpose.
  28266. */
  28267. class NodeCode {
  28268. /**
  28269. * Constructs a new code node.
  28270. *
  28271. * @param {String} name - The name of the code.
  28272. * @param {String} type - The node type.
  28273. * @param {String} [code=''] - The native shader code.
  28274. */
  28275. constructor( name, type, code = '' ) {
  28276. /**
  28277. * The name of the code.
  28278. *
  28279. * @type {String}
  28280. */
  28281. this.name = name;
  28282. /**
  28283. * The node type.
  28284. *
  28285. * @type {String}
  28286. */
  28287. this.type = type;
  28288. /**
  28289. * The native shader code.
  28290. *
  28291. * @type {String}
  28292. * @default ''
  28293. */
  28294. this.code = code;
  28295. Object.defineProperty( this, 'isNodeCode', { value: true } );
  28296. }
  28297. }
  28298. let _id$5 = 0;
  28299. /**
  28300. * This utility class is used in {@link NodeBuilder} as an internal
  28301. * cache data structure for node data.
  28302. */
  28303. class NodeCache {
  28304. /**
  28305. * Constructs a new node cache.
  28306. *
  28307. * @param {NodeCache?} parent - A reference to a parent cache.
  28308. */
  28309. constructor( parent = null ) {
  28310. /**
  28311. * The id of the cache.
  28312. *
  28313. * @type {Number}
  28314. * @readonly
  28315. */
  28316. this.id = _id$5 ++;
  28317. /**
  28318. * A weak map for managing node data.
  28319. *
  28320. * @type {WeakMap<Node, Object>}
  28321. */
  28322. this.nodesData = new WeakMap();
  28323. /**
  28324. * Reference to a parent node cache.
  28325. *
  28326. * @type {NodeCache?}
  28327. * @default null
  28328. */
  28329. this.parent = parent;
  28330. }
  28331. /**
  28332. * Returns the data for the given node.
  28333. *
  28334. * @param {Node} node - The node.
  28335. * @return {Object?} The data for the node.
  28336. */
  28337. getData( node ) {
  28338. let data = this.nodesData.get( node );
  28339. if ( data === undefined && this.parent !== null ) {
  28340. data = this.parent.getData( node );
  28341. }
  28342. return data;
  28343. }
  28344. /**
  28345. * Sets the data for a given node.
  28346. *
  28347. * @param {Node} node - The node.
  28348. * @param {Object} data - The data that should be cached.
  28349. */
  28350. setData( node, data ) {
  28351. this.nodesData.set( node, data );
  28352. }
  28353. }
  28354. /**
  28355. * {@link NodeBuilder} is going to create instances of this class during the build process
  28356. * of nodes. They represent the final shader struct data that are going to be generated
  28357. * by the builder. A dictionary of struct types is maintained in {@link NodeBuilder#structs}
  28358. * for this purpose.
  28359. */
  28360. class StructTypeNode extends Node {
  28361. static get type() {
  28362. return 'StructTypeNode';
  28363. }
  28364. /**
  28365. * Constructs a new struct type node.
  28366. *
  28367. * @param {String} name - The name of the struct.
  28368. * @param {Array<String>} types - An array of types.
  28369. */
  28370. constructor( name, types ) {
  28371. super();
  28372. /**
  28373. * The name of the struct.
  28374. *
  28375. * @type {String}
  28376. */
  28377. this.name = name;
  28378. /**
  28379. * An array of types.
  28380. *
  28381. * @type {Array<String>}
  28382. */
  28383. this.types = types;
  28384. /**
  28385. * This flag can be used for type testing.
  28386. *
  28387. * @type {Boolean}
  28388. * @readonly
  28389. * @default true
  28390. */
  28391. this.isStructTypeNode = true;
  28392. }
  28393. /**
  28394. * Returns the member types.
  28395. *
  28396. * @return {Array<String>} The types.
  28397. */
  28398. getMemberTypes() {
  28399. return this.types;
  28400. }
  28401. }
  28402. /**
  28403. * Abstract base class for uniforms.
  28404. *
  28405. * @abstract
  28406. * @private
  28407. */
  28408. class Uniform {
  28409. /**
  28410. * Constructs a new uniform.
  28411. *
  28412. * @param {String} name - The uniform's name.
  28413. * @param {Any} value - The uniform's value.
  28414. */
  28415. constructor( name, value ) {
  28416. /**
  28417. * The uniform's name.
  28418. *
  28419. * @type {String}
  28420. */
  28421. this.name = name;
  28422. /**
  28423. * The uniform's value.
  28424. *
  28425. * @type {Any}
  28426. */
  28427. this.value = value;
  28428. /**
  28429. * Used to build the uniform buffer according to the STD140 layout.
  28430. * Derived uniforms will set this property to a data type specific
  28431. * value.
  28432. *
  28433. * @type {Number}
  28434. */
  28435. this.boundary = 0;
  28436. /**
  28437. * The item size. Derived uniforms will set this property to a data
  28438. * type specific value.
  28439. *
  28440. * @type {Number}
  28441. */
  28442. this.itemSize = 0;
  28443. /**
  28444. * This property is set by {@link UniformsGroup} and marks
  28445. * the start position in the uniform buffer.
  28446. *
  28447. * @type {Number}
  28448. */
  28449. this.offset = 0;
  28450. }
  28451. /**
  28452. * Sets the uniform's value.
  28453. *
  28454. * @param {Any} value - The value to set.
  28455. */
  28456. setValue( value ) {
  28457. this.value = value;
  28458. }
  28459. /**
  28460. * Returns the uniform's value.
  28461. *
  28462. * @return {Any} The value.
  28463. */
  28464. getValue() {
  28465. return this.value;
  28466. }
  28467. }
  28468. /**
  28469. * Represents a Number uniform.
  28470. *
  28471. * @private
  28472. * @augments Uniform
  28473. */
  28474. class NumberUniform extends Uniform {
  28475. /**
  28476. * Constructs a new Number uniform.
  28477. *
  28478. * @param {String} name - The uniform's name.
  28479. * @param {Number} value - The uniform's value.
  28480. */
  28481. constructor( name, value = 0 ) {
  28482. super( name, value );
  28483. /**
  28484. * This flag can be used for type testing.
  28485. *
  28486. * @type {Boolean}
  28487. * @readonly
  28488. * @default true
  28489. */
  28490. this.isNumberUniform = true;
  28491. this.boundary = 4;
  28492. this.itemSize = 1;
  28493. }
  28494. }
  28495. /**
  28496. * Represents a Vector2 uniform.
  28497. *
  28498. * @private
  28499. * @augments Uniform
  28500. */
  28501. class Vector2Uniform extends Uniform {
  28502. /**
  28503. * Constructs a new Number uniform.
  28504. *
  28505. * @param {String} name - The uniform's name.
  28506. * @param {Vector2} value - The uniform's value.
  28507. */
  28508. constructor( name, value = new Vector2() ) {
  28509. super( name, value );
  28510. /**
  28511. * This flag can be used for type testing.
  28512. *
  28513. * @type {Boolean}
  28514. * @readonly
  28515. * @default true
  28516. */
  28517. this.isVector2Uniform = true;
  28518. this.boundary = 8;
  28519. this.itemSize = 2;
  28520. }
  28521. }
  28522. /**
  28523. * Represents a Vector3 uniform.
  28524. *
  28525. * @private
  28526. * @augments Uniform
  28527. */
  28528. class Vector3Uniform extends Uniform {
  28529. /**
  28530. * Constructs a new Number uniform.
  28531. *
  28532. * @param {String} name - The uniform's name.
  28533. * @param {Vector3} value - The uniform's value.
  28534. */
  28535. constructor( name, value = new Vector3() ) {
  28536. super( name, value );
  28537. /**
  28538. * This flag can be used for type testing.
  28539. *
  28540. * @type {Boolean}
  28541. * @readonly
  28542. * @default true
  28543. */
  28544. this.isVector3Uniform = true;
  28545. this.boundary = 16;
  28546. this.itemSize = 3;
  28547. }
  28548. }
  28549. /**
  28550. * Represents a Vector4 uniform.
  28551. *
  28552. * @private
  28553. * @augments Uniform
  28554. */
  28555. class Vector4Uniform extends Uniform {
  28556. /**
  28557. * Constructs a new Number uniform.
  28558. *
  28559. * @param {String} name - The uniform's name.
  28560. * @param {Vector4} value - The uniform's value.
  28561. */
  28562. constructor( name, value = new Vector4() ) {
  28563. super( name, value );
  28564. /**
  28565. * This flag can be used for type testing.
  28566. *
  28567. * @type {Boolean}
  28568. * @readonly
  28569. * @default true
  28570. */
  28571. this.isVector4Uniform = true;
  28572. this.boundary = 16;
  28573. this.itemSize = 4;
  28574. }
  28575. }
  28576. /**
  28577. * Represents a Color uniform.
  28578. *
  28579. * @private
  28580. * @augments Uniform
  28581. */
  28582. class ColorUniform extends Uniform {
  28583. /**
  28584. * Constructs a new Number uniform.
  28585. *
  28586. * @param {String} name - The uniform's name.
  28587. * @param {Color} value - The uniform's value.
  28588. */
  28589. constructor( name, value = new Color() ) {
  28590. super( name, value );
  28591. /**
  28592. * This flag can be used for type testing.
  28593. *
  28594. * @type {Boolean}
  28595. * @readonly
  28596. * @default true
  28597. */
  28598. this.isColorUniform = true;
  28599. this.boundary = 16;
  28600. this.itemSize = 3;
  28601. }
  28602. }
  28603. /**
  28604. * Represents a Matrix3 uniform.
  28605. *
  28606. * @private
  28607. * @augments Uniform
  28608. */
  28609. class Matrix3Uniform extends Uniform {
  28610. /**
  28611. * Constructs a new Number uniform.
  28612. *
  28613. * @param {String} name - The uniform's name.
  28614. * @param {Matrix3} value - The uniform's value.
  28615. */
  28616. constructor( name, value = new Matrix3() ) {
  28617. super( name, value );
  28618. /**
  28619. * This flag can be used for type testing.
  28620. *
  28621. * @type {Boolean}
  28622. * @readonly
  28623. * @default true
  28624. */
  28625. this.isMatrix3Uniform = true;
  28626. this.boundary = 48;
  28627. this.itemSize = 12;
  28628. }
  28629. }
  28630. /**
  28631. * Represents a Matrix4 uniform.
  28632. *
  28633. * @private
  28634. * @augments Uniform
  28635. */
  28636. class Matrix4Uniform extends Uniform {
  28637. /**
  28638. * Constructs a new Number uniform.
  28639. *
  28640. * @param {String} name - The uniform's name.
  28641. * @param {Matrix4} value - The uniform's value.
  28642. */
  28643. constructor( name, value = new Matrix4() ) {
  28644. super( name, value );
  28645. /**
  28646. * This flag can be used for type testing.
  28647. *
  28648. * @type {Boolean}
  28649. * @readonly
  28650. * @default true
  28651. */
  28652. this.isMatrix4Uniform = true;
  28653. this.boundary = 64;
  28654. this.itemSize = 16;
  28655. }
  28656. }
  28657. /**
  28658. * A special form of Number uniform binding type.
  28659. * It's value is managed by a node object.
  28660. *
  28661. * @private
  28662. * @augments NumberUniform
  28663. */
  28664. class NumberNodeUniform extends NumberUniform {
  28665. /**
  28666. * Constructs a new node-based Number uniform.
  28667. *
  28668. * @param {NodeUniform} nodeUniform - The node uniform.
  28669. */
  28670. constructor( nodeUniform ) {
  28671. super( nodeUniform.name, nodeUniform.value );
  28672. /**
  28673. * The node uniform.
  28674. *
  28675. * @type {NodeUniform}
  28676. */
  28677. this.nodeUniform = nodeUniform;
  28678. }
  28679. /**
  28680. * Overwritten to return the value of the node uniform.
  28681. *
  28682. * @return {Number} The value.
  28683. */
  28684. getValue() {
  28685. return this.nodeUniform.value;
  28686. }
  28687. /**
  28688. * Returns the node uniform data type.
  28689. *
  28690. * @return {String} The data type.
  28691. */
  28692. getType() {
  28693. return this.nodeUniform.type;
  28694. }
  28695. }
  28696. /**
  28697. * A special form of Vector2 uniform binding type.
  28698. * It's value is managed by a node object.
  28699. *
  28700. * @private
  28701. * @augments Vector2Uniform
  28702. */
  28703. class Vector2NodeUniform extends Vector2Uniform {
  28704. /**
  28705. * Constructs a new node-based Vector2 uniform.
  28706. *
  28707. * @param {NodeUniform} nodeUniform - The node uniform.
  28708. */
  28709. constructor( nodeUniform ) {
  28710. super( nodeUniform.name, nodeUniform.value );
  28711. /**
  28712. * The node uniform.
  28713. *
  28714. * @type {NodeUniform}
  28715. */
  28716. this.nodeUniform = nodeUniform;
  28717. }
  28718. /**
  28719. * Overwritten to return the value of the node uniform.
  28720. *
  28721. * @return {Vector2} The value.
  28722. */
  28723. getValue() {
  28724. return this.nodeUniform.value;
  28725. }
  28726. /**
  28727. * Returns the node uniform data type.
  28728. *
  28729. * @return {String} The data type.
  28730. */
  28731. getType() {
  28732. return this.nodeUniform.type;
  28733. }
  28734. }
  28735. /**
  28736. * A special form of Vector3 uniform binding type.
  28737. * It's value is managed by a node object.
  28738. *
  28739. * @private
  28740. * @augments Vector3Uniform
  28741. */
  28742. class Vector3NodeUniform extends Vector3Uniform {
  28743. /**
  28744. * Constructs a new node-based Vector3 uniform.
  28745. *
  28746. * @param {NodeUniform} nodeUniform - The node uniform.
  28747. */
  28748. constructor( nodeUniform ) {
  28749. super( nodeUniform.name, nodeUniform.value );
  28750. /**
  28751. * The node uniform.
  28752. *
  28753. * @type {NodeUniform}
  28754. */
  28755. this.nodeUniform = nodeUniform;
  28756. }
  28757. /**
  28758. * Overwritten to return the value of the node uniform.
  28759. *
  28760. * @return {Vector3} The value.
  28761. */
  28762. getValue() {
  28763. return this.nodeUniform.value;
  28764. }
  28765. /**
  28766. * Returns the node uniform data type.
  28767. *
  28768. * @return {String} The data type.
  28769. */
  28770. getType() {
  28771. return this.nodeUniform.type;
  28772. }
  28773. }
  28774. /**
  28775. * A special form of Vector4 uniform binding type.
  28776. * It's value is managed by a node object.
  28777. *
  28778. * @private
  28779. * @augments Vector4Uniform
  28780. */
  28781. class Vector4NodeUniform extends Vector4Uniform {
  28782. /**
  28783. * Constructs a new node-based Vector4 uniform.
  28784. *
  28785. * @param {NodeUniform} nodeUniform - The node uniform.
  28786. */
  28787. constructor( nodeUniform ) {
  28788. super( nodeUniform.name, nodeUniform.value );
  28789. /**
  28790. * The node uniform.
  28791. *
  28792. * @type {NodeUniform}
  28793. */
  28794. this.nodeUniform = nodeUniform;
  28795. }
  28796. /**
  28797. * Overwritten to return the value of the node uniform.
  28798. *
  28799. * @return {Vector4} The value.
  28800. */
  28801. getValue() {
  28802. return this.nodeUniform.value;
  28803. }
  28804. /**
  28805. * Returns the node uniform data type.
  28806. *
  28807. * @return {String} The data type.
  28808. */
  28809. getType() {
  28810. return this.nodeUniform.type;
  28811. }
  28812. }
  28813. /**
  28814. * A special form of Color uniform binding type.
  28815. * It's value is managed by a node object.
  28816. *
  28817. * @private
  28818. * @augments ColorUniform
  28819. */
  28820. class ColorNodeUniform extends ColorUniform {
  28821. /**
  28822. * Constructs a new node-based Color uniform.
  28823. *
  28824. * @param {NodeUniform} nodeUniform - The node uniform.
  28825. */
  28826. constructor( nodeUniform ) {
  28827. super( nodeUniform.name, nodeUniform.value );
  28828. /**
  28829. * The node uniform.
  28830. *
  28831. * @type {NodeUniform}
  28832. */
  28833. this.nodeUniform = nodeUniform;
  28834. }
  28835. /**
  28836. * Overwritten to return the value of the node uniform.
  28837. *
  28838. * @return {Color} The value.
  28839. */
  28840. getValue() {
  28841. return this.nodeUniform.value;
  28842. }
  28843. /**
  28844. * Returns the node uniform data type.
  28845. *
  28846. * @return {String} The data type.
  28847. */
  28848. getType() {
  28849. return this.nodeUniform.type;
  28850. }
  28851. }
  28852. /**
  28853. * A special form of Matrix3 uniform binding type.
  28854. * It's value is managed by a node object.
  28855. *
  28856. * @private
  28857. * @augments Matrix3Uniform
  28858. */
  28859. class Matrix3NodeUniform extends Matrix3Uniform {
  28860. /**
  28861. * Constructs a new node-based Matrix3 uniform.
  28862. *
  28863. * @param {NodeUniform} nodeUniform - The node uniform.
  28864. */
  28865. constructor( nodeUniform ) {
  28866. super( nodeUniform.name, nodeUniform.value );
  28867. /**
  28868. * The node uniform.
  28869. *
  28870. * @type {NodeUniform}
  28871. */
  28872. this.nodeUniform = nodeUniform;
  28873. }
  28874. /**
  28875. * Overwritten to return the value of the node uniform.
  28876. *
  28877. * @return {Matrix3} The value.
  28878. */
  28879. getValue() {
  28880. return this.nodeUniform.value;
  28881. }
  28882. /**
  28883. * Returns the node uniform data type.
  28884. *
  28885. * @return {String} The data type.
  28886. */
  28887. getType() {
  28888. return this.nodeUniform.type;
  28889. }
  28890. }
  28891. /**
  28892. * A special form of Matrix4 uniform binding type.
  28893. * It's value is managed by a node object.
  28894. *
  28895. * @private
  28896. * @augments Matrix4Uniform
  28897. */
  28898. class Matrix4NodeUniform extends Matrix4Uniform {
  28899. /**
  28900. * Constructs a new node-based Matrix4 uniform.
  28901. *
  28902. * @param {NodeUniform} nodeUniform - The node uniform.
  28903. */
  28904. constructor( nodeUniform ) {
  28905. super( nodeUniform.name, nodeUniform.value );
  28906. /**
  28907. * The node uniform.
  28908. *
  28909. * @type {NodeUniform}
  28910. */
  28911. this.nodeUniform = nodeUniform;
  28912. }
  28913. /**
  28914. * Overwritten to return the value of the node uniform.
  28915. *
  28916. * @return {Matrix4} The value.
  28917. */
  28918. getValue() {
  28919. return this.nodeUniform.value;
  28920. }
  28921. /**
  28922. * Returns the node uniform data type.
  28923. *
  28924. * @return {String} The data type.
  28925. */
  28926. getType() {
  28927. return this.nodeUniform.type;
  28928. }
  28929. }
  28930. const LOD_MIN = 4;
  28931. // The standard deviations (radians) associated with the extra mips. These are
  28932. // chosen to approximate a Trowbridge-Reitz distribution function times the
  28933. // geometric shadowing function. These sigma values squared must match the
  28934. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  28935. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  28936. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  28937. // samples and exit early, but not recompile the shader.
  28938. const MAX_SAMPLES = 20;
  28939. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  28940. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  28941. const _clearColor = /*@__PURE__*/ new Color();
  28942. let _oldTarget = null;
  28943. let _oldActiveCubeFace = 0;
  28944. let _oldActiveMipmapLevel = 0;
  28945. // Golden Ratio
  28946. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  28947. const INV_PHI = 1 / PHI;
  28948. // Vertices of a dodecahedron (except the opposites, which represent the
  28949. // same axis), used as axis directions evenly spread on a sphere.
  28950. const _axisDirections = [
  28951. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  28952. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  28953. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  28954. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  28955. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  28956. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  28957. /*@__PURE__*/ new Vector3( - 1, 1, - 1 ),
  28958. /*@__PURE__*/ new Vector3( 1, 1, - 1 ),
  28959. /*@__PURE__*/ new Vector3( - 1, 1, 1 ),
  28960. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  28961. ];
  28962. // maps blur materials to their uniforms dictionary
  28963. const _uniformsMap = new WeakMap();
  28964. // WebGPU Face indices
  28965. const _faceLib = [
  28966. 3, 1, 5,
  28967. 0, 4, 2
  28968. ];
  28969. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  28970. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  28971. /**
  28972. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  28973. * (PMREM) from a cubeMap environment texture. This allows different levels of
  28974. * blur to be quickly accessed based on material roughness. It is packed into a
  28975. * special CubeUV format that allows us to perform custom interpolation so that
  28976. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  28977. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  28978. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  28979. * higher roughness levels. In this way we maintain resolution to smoothly
  28980. * interpolate diffuse lighting while limiting sampling computation.
  28981. *
  28982. * Paper: Fast, Accurate Image-Based Lighting
  28983. * https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view
  28984. */
  28985. class PMREMGenerator {
  28986. constructor( renderer ) {
  28987. this._renderer = renderer;
  28988. this._pingPongRenderTarget = null;
  28989. this._lodMax = 0;
  28990. this._cubeSize = 0;
  28991. this._lodPlanes = [];
  28992. this._sizeLods = [];
  28993. this._sigmas = [];
  28994. this._lodMeshes = [];
  28995. this._blurMaterial = null;
  28996. this._cubemapMaterial = null;
  28997. this._equirectMaterial = null;
  28998. this._backgroundBox = null;
  28999. }
  29000. get _hasInitialized() {
  29001. return this._renderer.hasInitialized();
  29002. }
  29003. /**
  29004. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29005. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29006. * in radians to be applied to the scene before PMREM generation. Optional near
  29007. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29008. * is placed at the origin).
  29009. *
  29010. * @param {Scene} scene - The scene to be captured.
  29011. * @param {Number} [sigma=0] - The blur radius in radians.
  29012. * @param {Number} [near=0.1] - The near plane distance.
  29013. * @param {Number} [far=100] - The far plane distance.
  29014. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29015. * @return {RenderTarget} The resulting PMREM.
  29016. * @see fromSceneAsync
  29017. */
  29018. fromScene( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29019. this._setSize( 256 );
  29020. if ( this._hasInitialized === false ) {
  29021. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  29022. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29023. this.fromSceneAsync( scene, sigma, near, far, cubeUVRenderTarget );
  29024. return cubeUVRenderTarget;
  29025. }
  29026. _oldTarget = this._renderer.getRenderTarget();
  29027. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29028. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29029. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29030. cubeUVRenderTarget.depthBuffer = true;
  29031. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget );
  29032. if ( sigma > 0 ) {
  29033. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  29034. }
  29035. this._applyPMREM( cubeUVRenderTarget );
  29036. this._cleanup( cubeUVRenderTarget );
  29037. return cubeUVRenderTarget;
  29038. }
  29039. /**
  29040. * Generates a PMREM from a supplied Scene, which can be faster than using an
  29041. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  29042. * in radians to be applied to the scene before PMREM generation. Optional near
  29043. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  29044. * is placed at the origin).
  29045. *
  29046. * @param {Scene} scene - The scene to be captured.
  29047. * @param {Number} [sigma=0] - The blur radius in radians.
  29048. * @param {Number} [near=0.1] - The near plane distance.
  29049. * @param {Number} [far=100] - The far plane distance.
  29050. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29051. * @return {Promise<RenderTarget>} The resulting PMREM.
  29052. * @see fromScene
  29053. */
  29054. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, renderTarget = null ) {
  29055. if ( this._hasInitialized === false ) await this._renderer.init();
  29056. return this.fromScene( scene, sigma, near, far, renderTarget );
  29057. }
  29058. /**
  29059. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29060. * or HDR. The ideal input image size is 1k (1024 x 512),
  29061. * as this matches best with the 256 x 256 cubemap output.
  29062. *
  29063. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29064. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29065. * @return {RenderTarget} The resulting PMREM.
  29066. * @see fromEquirectangularAsync
  29067. */
  29068. fromEquirectangular( equirectangular, renderTarget = null ) {
  29069. if ( this._hasInitialized === false ) {
  29070. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  29071. this._setSizeFromTexture( equirectangular );
  29072. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29073. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  29074. return cubeUVRenderTarget;
  29075. }
  29076. return this._fromTexture( equirectangular, renderTarget );
  29077. }
  29078. /**
  29079. * Generates a PMREM from an equirectangular texture, which can be either LDR
  29080. * or HDR. The ideal input image size is 1k (1024 x 512),
  29081. * as this matches best with the 256 x 256 cubemap output.
  29082. *
  29083. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  29084. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29085. * @return {Promise<RenderTarget>} The resulting PMREM.
  29086. * @see fromEquirectangular
  29087. */
  29088. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  29089. if ( this._hasInitialized === false ) await this._renderer.init();
  29090. return this._fromTexture( equirectangular, renderTarget );
  29091. }
  29092. /**
  29093. * Generates a PMREM from an cubemap texture, which can be either LDR
  29094. * or HDR. The ideal input cube size is 256 x 256,
  29095. * as this matches best with the 256 x 256 cubemap output.
  29096. *
  29097. * @param {Texture} cubemap - The cubemap texture to be converted.
  29098. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29099. * @return {RenderTarget} The resulting PMREM.
  29100. * @see fromCubemapAsync
  29101. */
  29102. fromCubemap( cubemap, renderTarget = null ) {
  29103. if ( this._hasInitialized === false ) {
  29104. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  29105. this._setSizeFromTexture( cubemap );
  29106. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29107. this.fromCubemapAsync( cubemap, renderTarget );
  29108. return cubeUVRenderTarget;
  29109. }
  29110. return this._fromTexture( cubemap, renderTarget );
  29111. }
  29112. /**
  29113. * Generates a PMREM from an cubemap texture, which can be either LDR
  29114. * or HDR. The ideal input cube size is 256 x 256,
  29115. * with the 256 x 256 cubemap output.
  29116. *
  29117. * @param {Texture} cubemap - The cubemap texture to be converted.
  29118. * @param {RenderTarget?} [renderTarget=null] - The render target to use.
  29119. * @return {Promise<RenderTarget>} The resulting PMREM.
  29120. * @see fromCubemap
  29121. */
  29122. async fromCubemapAsync( cubemap, renderTarget = null ) {
  29123. if ( this._hasInitialized === false ) await this._renderer.init();
  29124. return this._fromTexture( cubemap, renderTarget );
  29125. }
  29126. /**
  29127. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  29128. * your texture's network fetch for increased concurrency.
  29129. *
  29130. * @returns {Promise}
  29131. */
  29132. async compileCubemapShader() {
  29133. if ( this._cubemapMaterial === null ) {
  29134. this._cubemapMaterial = _getCubemapMaterial();
  29135. await this._compileMaterial( this._cubemapMaterial );
  29136. }
  29137. }
  29138. /**
  29139. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  29140. * your texture's network fetch for increased concurrency.
  29141. *
  29142. * @returns {Promise}
  29143. */
  29144. async compileEquirectangularShader() {
  29145. if ( this._equirectMaterial === null ) {
  29146. this._equirectMaterial = _getEquirectMaterial();
  29147. await this._compileMaterial( this._equirectMaterial );
  29148. }
  29149. }
  29150. /**
  29151. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  29152. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  29153. * one of them will cause any others to also become unusable.
  29154. */
  29155. dispose() {
  29156. this._dispose();
  29157. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  29158. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  29159. if ( this._backgroundBox !== null ) {
  29160. this._backgroundBox.geometry.dispose();
  29161. this._backgroundBox.material.dispose();
  29162. }
  29163. }
  29164. // private interface
  29165. _setSizeFromTexture( texture ) {
  29166. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  29167. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  29168. } else { // Equirectangular
  29169. this._setSize( texture.image.width / 4 );
  29170. }
  29171. }
  29172. _setSize( cubeSize ) {
  29173. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  29174. this._cubeSize = Math.pow( 2, this._lodMax );
  29175. }
  29176. _dispose() {
  29177. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  29178. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  29179. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  29180. this._lodPlanes[ i ].dispose();
  29181. }
  29182. }
  29183. _cleanup( outputTarget ) {
  29184. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  29185. outputTarget.scissorTest = false;
  29186. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  29187. }
  29188. _fromTexture( texture, renderTarget ) {
  29189. this._setSizeFromTexture( texture );
  29190. _oldTarget = this._renderer.getRenderTarget();
  29191. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  29192. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  29193. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  29194. this._textureToCubeUV( texture, cubeUVRenderTarget );
  29195. this._applyPMREM( cubeUVRenderTarget );
  29196. this._cleanup( cubeUVRenderTarget );
  29197. return cubeUVRenderTarget;
  29198. }
  29199. _allocateTargets() {
  29200. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  29201. const height = 4 * this._cubeSize;
  29202. const params = {
  29203. magFilter: LinearFilter,
  29204. minFilter: LinearFilter,
  29205. generateMipmaps: false,
  29206. type: HalfFloatType,
  29207. format: RGBAFormat,
  29208. colorSpace: LinearSRGBColorSpace,
  29209. //depthBuffer: false
  29210. };
  29211. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  29212. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  29213. if ( this._pingPongRenderTarget !== null ) {
  29214. this._dispose();
  29215. }
  29216. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  29217. const { _lodMax } = this;
  29218. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  29219. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  29220. }
  29221. return cubeUVRenderTarget;
  29222. }
  29223. async _compileMaterial( material ) {
  29224. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  29225. await this._renderer.compile( tmpMesh, _flatCamera );
  29226. }
  29227. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget ) {
  29228. const cubeCamera = _cubeCamera;
  29229. cubeCamera.near = near;
  29230. cubeCamera.far = far;
  29231. // px, py, pz, nx, ny, nz
  29232. const upSign = [ 1, 1, 1, 1, - 1, 1 ];
  29233. const forwardSign = [ 1, - 1, 1, - 1, 1, - 1 ];
  29234. const renderer = this._renderer;
  29235. const originalAutoClear = renderer.autoClear;
  29236. renderer.getClearColor( _clearColor );
  29237. renderer.autoClear = false;
  29238. let backgroundBox = this._backgroundBox;
  29239. if ( backgroundBox === null ) {
  29240. const backgroundMaterial = new MeshBasicMaterial( {
  29241. name: 'PMREM.Background',
  29242. side: BackSide,
  29243. depthWrite: false,
  29244. depthTest: false
  29245. } );
  29246. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  29247. }
  29248. let useSolidColor = false;
  29249. const background = scene.background;
  29250. if ( background ) {
  29251. if ( background.isColor ) {
  29252. backgroundBox.material.color.copy( background );
  29253. scene.background = null;
  29254. useSolidColor = true;
  29255. }
  29256. } else {
  29257. backgroundBox.material.color.copy( _clearColor );
  29258. useSolidColor = true;
  29259. }
  29260. renderer.setRenderTarget( cubeUVRenderTarget );
  29261. renderer.clear();
  29262. if ( useSolidColor ) {
  29263. renderer.render( backgroundBox, cubeCamera );
  29264. }
  29265. for ( let i = 0; i < 6; i ++ ) {
  29266. const col = i % 3;
  29267. if ( col === 0 ) {
  29268. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29269. cubeCamera.lookAt( forwardSign[ i ], 0, 0 );
  29270. } else if ( col === 1 ) {
  29271. cubeCamera.up.set( 0, 0, upSign[ i ] );
  29272. cubeCamera.lookAt( 0, forwardSign[ i ], 0 );
  29273. } else {
  29274. cubeCamera.up.set( 0, upSign[ i ], 0 );
  29275. cubeCamera.lookAt( 0, 0, forwardSign[ i ] );
  29276. }
  29277. const size = this._cubeSize;
  29278. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  29279. renderer.render( scene, cubeCamera );
  29280. }
  29281. renderer.autoClear = originalAutoClear;
  29282. scene.background = background;
  29283. }
  29284. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  29285. const renderer = this._renderer;
  29286. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  29287. if ( isCubeTexture ) {
  29288. if ( this._cubemapMaterial === null ) {
  29289. this._cubemapMaterial = _getCubemapMaterial( texture );
  29290. }
  29291. } else {
  29292. if ( this._equirectMaterial === null ) {
  29293. this._equirectMaterial = _getEquirectMaterial( texture );
  29294. }
  29295. }
  29296. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  29297. material.fragmentNode.value = texture;
  29298. const mesh = this._lodMeshes[ 0 ];
  29299. mesh.material = material;
  29300. const size = this._cubeSize;
  29301. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  29302. renderer.setRenderTarget( cubeUVRenderTarget );
  29303. renderer.render( mesh, _flatCamera );
  29304. }
  29305. _applyPMREM( cubeUVRenderTarget ) {
  29306. const renderer = this._renderer;
  29307. const autoClear = renderer.autoClear;
  29308. renderer.autoClear = false;
  29309. const n = this._lodPlanes.length;
  29310. for ( let i = 1; i < n; i ++ ) {
  29311. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  29312. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  29313. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  29314. }
  29315. renderer.autoClear = autoClear;
  29316. }
  29317. /**
  29318. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  29319. * vertically and horizontally, but this breaks down on a cube. Here we apply
  29320. * the blur latitudinally (around the poles), and then longitudinally (towards
  29321. * the poles) to approximate the orthogonally-separable blur. It is least
  29322. * accurate at the poles, but still does a decent job.
  29323. *
  29324. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  29325. * @param {Number} lodIn - The input level-of-detail.
  29326. * @param {Number} lodOut - The output level-of-detail.
  29327. * @param {Number} sigma - The blur radius in radians.
  29328. * @param {Vector3} [poleAxis] - The pole axis.
  29329. */
  29330. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  29331. const pingPongRenderTarget = this._pingPongRenderTarget;
  29332. this._halfBlur(
  29333. cubeUVRenderTarget,
  29334. pingPongRenderTarget,
  29335. lodIn,
  29336. lodOut,
  29337. sigma,
  29338. 'latitudinal',
  29339. poleAxis );
  29340. this._halfBlur(
  29341. pingPongRenderTarget,
  29342. cubeUVRenderTarget,
  29343. lodOut,
  29344. lodOut,
  29345. sigma,
  29346. 'longitudinal',
  29347. poleAxis );
  29348. }
  29349. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  29350. const renderer = this._renderer;
  29351. const blurMaterial = this._blurMaterial;
  29352. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  29353. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  29354. }
  29355. // Number of standard deviations at which to cut off the discrete approximation.
  29356. const STANDARD_DEVIATIONS = 3;
  29357. const blurMesh = this._lodMeshes[ lodOut ];
  29358. blurMesh.material = blurMaterial;
  29359. const blurUniforms = _uniformsMap.get( blurMaterial );
  29360. const pixels = this._sizeLods[ lodIn ] - 1;
  29361. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  29362. const sigmaPixels = sigmaRadians / radiansPerPixel;
  29363. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  29364. if ( samples > MAX_SAMPLES ) {
  29365. console.warn( `sigmaRadians, ${
  29366. sigmaRadians}, is too large and will clip, as it requested ${
  29367. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  29368. }
  29369. const weights = [];
  29370. let sum = 0;
  29371. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  29372. const x = i / sigmaPixels;
  29373. const weight = Math.exp( - x * x / 2 );
  29374. weights.push( weight );
  29375. if ( i === 0 ) {
  29376. sum += weight;
  29377. } else if ( i < samples ) {
  29378. sum += 2 * weight;
  29379. }
  29380. }
  29381. for ( let i = 0; i < weights.length; i ++ ) {
  29382. weights[ i ] = weights[ i ] / sum;
  29383. }
  29384. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  29385. blurUniforms.envMap.value = targetIn.texture;
  29386. blurUniforms.samples.value = samples;
  29387. blurUniforms.weights.array = weights;
  29388. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  29389. if ( poleAxis ) {
  29390. blurUniforms.poleAxis.value = poleAxis;
  29391. }
  29392. const { _lodMax } = this;
  29393. blurUniforms.dTheta.value = radiansPerPixel;
  29394. blurUniforms.mipInt.value = _lodMax - lodIn;
  29395. const outputSize = this._sizeLods[ lodOut ];
  29396. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  29397. const y = 4 * ( this._cubeSize - outputSize );
  29398. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  29399. renderer.setRenderTarget( targetOut );
  29400. renderer.render( blurMesh, _flatCamera );
  29401. }
  29402. }
  29403. function _createPlanes( lodMax ) {
  29404. const lodPlanes = [];
  29405. const sizeLods = [];
  29406. const sigmas = [];
  29407. const lodMeshes = [];
  29408. let lod = lodMax;
  29409. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  29410. for ( let i = 0; i < totalLods; i ++ ) {
  29411. const sizeLod = Math.pow( 2, lod );
  29412. sizeLods.push( sizeLod );
  29413. let sigma = 1.0 / sizeLod;
  29414. if ( i > lodMax - LOD_MIN ) {
  29415. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  29416. } else if ( i === 0 ) {
  29417. sigma = 0;
  29418. }
  29419. sigmas.push( sigma );
  29420. const texelSize = 1.0 / ( sizeLod - 2 );
  29421. const min = - texelSize;
  29422. const max = 1 + texelSize;
  29423. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  29424. const cubeFaces = 6;
  29425. const vertices = 6;
  29426. const positionSize = 3;
  29427. const uvSize = 2;
  29428. const faceIndexSize = 1;
  29429. const position = new Float32Array( positionSize * vertices * cubeFaces );
  29430. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  29431. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  29432. for ( let face = 0; face < cubeFaces; face ++ ) {
  29433. const x = ( face % 3 ) * 2 / 3 - 1;
  29434. const y = face > 2 ? 0 : - 1;
  29435. const coordinates = [
  29436. x, y, 0,
  29437. x + 2 / 3, y, 0,
  29438. x + 2 / 3, y + 1, 0,
  29439. x, y, 0,
  29440. x + 2 / 3, y + 1, 0,
  29441. x, y + 1, 0
  29442. ];
  29443. const faceIdx = _faceLib[ face ];
  29444. position.set( coordinates, positionSize * vertices * faceIdx );
  29445. uv.set( uv1, uvSize * vertices * faceIdx );
  29446. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  29447. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  29448. }
  29449. const planes = new BufferGeometry();
  29450. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  29451. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  29452. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  29453. lodPlanes.push( planes );
  29454. lodMeshes.push( new Mesh( planes, null ) );
  29455. if ( lod > LOD_MIN ) {
  29456. lod --;
  29457. }
  29458. }
  29459. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  29460. }
  29461. function _createRenderTarget( width, height, params ) {
  29462. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  29463. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  29464. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  29465. cubeUVRenderTarget.texture.isPMREMTexture = true;
  29466. cubeUVRenderTarget.scissorTest = true;
  29467. return cubeUVRenderTarget;
  29468. }
  29469. function _setViewport( target, x, y, width, height ) {
  29470. target.viewport.set( x, y, width, height );
  29471. target.scissor.set( x, y, width, height );
  29472. }
  29473. function _getMaterial( type ) {
  29474. const material = new NodeMaterial();
  29475. material.depthTest = false;
  29476. material.depthWrite = false;
  29477. material.blending = NoBlending;
  29478. material.name = `PMREM_${ type }`;
  29479. return material;
  29480. }
  29481. function _getBlurShader( lodMax, width, height ) {
  29482. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  29483. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  29484. const dTheta = uniform( 0 );
  29485. const n = float( MAX_SAMPLES );
  29486. const latitudinal = uniform( 0 ); // false, bool
  29487. const samples = uniform( 1 ); // int
  29488. const envMap = texture( null );
  29489. const mipInt = uniform( 0 ); // int
  29490. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  29491. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  29492. const CUBEUV_MAX_MIP = float( lodMax );
  29493. const materialUniforms = {
  29494. n,
  29495. latitudinal,
  29496. weights,
  29497. poleAxis,
  29498. outputDirection: _outputDirection,
  29499. dTheta,
  29500. samples,
  29501. envMap,
  29502. mipInt,
  29503. CUBEUV_TEXEL_WIDTH,
  29504. CUBEUV_TEXEL_HEIGHT,
  29505. CUBEUV_MAX_MIP
  29506. };
  29507. const material = _getMaterial( 'blur' );
  29508. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  29509. _uniformsMap.set( material, materialUniforms );
  29510. return material;
  29511. }
  29512. function _getCubemapMaterial( envTexture ) {
  29513. const material = _getMaterial( 'cubemap' );
  29514. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  29515. return material;
  29516. }
  29517. function _getEquirectMaterial( envTexture ) {
  29518. const material = _getMaterial( 'equirect' );
  29519. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  29520. return material;
  29521. }
  29522. const rendererCache = new WeakMap();
  29523. const typeFromArray = new Map( [
  29524. [ Int8Array, 'int' ],
  29525. [ Int16Array, 'int' ],
  29526. [ Int32Array, 'int' ],
  29527. [ Uint8Array, 'uint' ],
  29528. [ Uint16Array, 'uint' ],
  29529. [ Uint32Array, 'uint' ],
  29530. [ Float32Array, 'float' ]
  29531. ] );
  29532. const toFloat = ( value ) => {
  29533. if ( /e/g.test( value ) ) {
  29534. return String( value ).replace( /\+/g, '' );
  29535. } else {
  29536. value = Number( value );
  29537. return value + ( value % 1 ? '' : '.0' );
  29538. }
  29539. };
  29540. /**
  29541. * Base class for builders which generate a shader program based
  29542. * on a 3D object and its node material definition.
  29543. */
  29544. class NodeBuilder {
  29545. /**
  29546. * Constructs a new node builder.
  29547. *
  29548. * @param {Object3D} object - The 3D object.
  29549. * @param {Renderer} renderer - The current renderer.
  29550. * @param {NodeParser} parser - A reference to a node parser.
  29551. */
  29552. constructor( object, renderer, parser ) {
  29553. /**
  29554. * The 3D object.
  29555. *
  29556. * @type {Object3D}
  29557. */
  29558. this.object = object;
  29559. /**
  29560. * The material of the 3D object.
  29561. *
  29562. * @type {Material?}
  29563. */
  29564. this.material = ( object && object.material ) || null;
  29565. /**
  29566. * The geometry of the 3D object.
  29567. *
  29568. * @type {BufferGeometry?}
  29569. */
  29570. this.geometry = ( object && object.geometry ) || null;
  29571. /**
  29572. * The current renderer.
  29573. *
  29574. * @type {Renderer}
  29575. */
  29576. this.renderer = renderer;
  29577. /**
  29578. * A reference to a node parser.
  29579. *
  29580. * @type {NodeParser}
  29581. */
  29582. this.parser = parser;
  29583. /**
  29584. * The scene the 3D object belongs to.
  29585. *
  29586. * @type {Scene?}
  29587. * @default null
  29588. */
  29589. this.scene = null;
  29590. /**
  29591. * The camera the 3D object is rendered with.
  29592. *
  29593. * @type {Camera?}
  29594. * @default null
  29595. */
  29596. this.camera = null;
  29597. /**
  29598. * A list of all nodes the builder is processing
  29599. * for this 3D object.
  29600. *
  29601. * @type {Array<Node>}
  29602. */
  29603. this.nodes = [];
  29604. /**
  29605. * A list of all sequential nodes.
  29606. *
  29607. * @type {Array<Node>}
  29608. */
  29609. this.sequentialNodes = [];
  29610. /**
  29611. * A list of all nodes which {@link Node#update} method should be executed.
  29612. *
  29613. * @type {Array<Node>}
  29614. */
  29615. this.updateNodes = [];
  29616. /**
  29617. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  29618. *
  29619. * @type {Array<Node>}
  29620. */
  29621. this.updateBeforeNodes = [];
  29622. /**
  29623. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  29624. *
  29625. * @type {Array<Node>}
  29626. */
  29627. this.updateAfterNodes = [];
  29628. /**
  29629. * A dictionary that assigns each node to a unique hash.
  29630. *
  29631. * @type {Object<Number,Node>}
  29632. */
  29633. this.hashNodes = {};
  29634. /**
  29635. * A reference to a node material observer.
  29636. *
  29637. * @type {NodeMaterialObserver?}
  29638. * @default null
  29639. */
  29640. this.monitor = null;
  29641. /**
  29642. * A reference to the current lights node.
  29643. *
  29644. * @type {LightsNode?}
  29645. * @default null
  29646. */
  29647. this.lightsNode = null;
  29648. /**
  29649. * A reference to the current environment node.
  29650. *
  29651. * @type {Node?}
  29652. * @default null
  29653. */
  29654. this.environmentNode = null;
  29655. /**
  29656. * A reference to the current fog node.
  29657. *
  29658. * @type {FogNode?}
  29659. * @default null
  29660. */
  29661. this.fogNode = null;
  29662. /**
  29663. * The current clipping context.
  29664. *
  29665. * @type {ClippingContext?}
  29666. */
  29667. this.clippingContext = null;
  29668. /**
  29669. * The generated vertex shader.
  29670. *
  29671. * @type {String?}
  29672. */
  29673. this.vertexShader = null;
  29674. /**
  29675. * The generated fragment shader.
  29676. *
  29677. * @type {String?}
  29678. */
  29679. this.fragmentShader = null;
  29680. /**
  29681. * The generated compute shader.
  29682. *
  29683. * @type {String?}
  29684. */
  29685. this.computeShader = null;
  29686. /**
  29687. * Nodes used in the primary flow of code generation.
  29688. *
  29689. * @type {Object<String,Array<Node>>}
  29690. */
  29691. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  29692. /**
  29693. * Nodes code from `.flowNodes`.
  29694. *
  29695. * @type {Object<String,String>}
  29696. */
  29697. this.flowCode = { vertex: '', fragment: '', compute: '' };
  29698. /**
  29699. * This dictionary holds the node uniforms of the builder.
  29700. * The uniforms are maintained in an array for each shader stage.
  29701. *
  29702. * @type {Object}
  29703. */
  29704. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  29705. /**
  29706. * This dictionary holds the output structs of the builder.
  29707. * The structs are maintained in an array for each shader stage.
  29708. *
  29709. * @type {Object}
  29710. */
  29711. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  29712. /**
  29713. * This dictionary holds the bindings for each shader stage.
  29714. *
  29715. * @type {Object}
  29716. */
  29717. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  29718. /**
  29719. * This dictionary maintains the binding indices per bind group.
  29720. *
  29721. * @type {Object}
  29722. */
  29723. this.bindingsIndexes = {};
  29724. /**
  29725. * Reference to the array of bind groups.
  29726. *
  29727. * @type {Array<BindGroup>?}
  29728. */
  29729. this.bindGroups = null;
  29730. /**
  29731. * This array holds the node attributes of this builder
  29732. * created via {@link AttributeNode}.
  29733. *
  29734. * @type {Array<NodeAttribute>}
  29735. */
  29736. this.attributes = [];
  29737. /**
  29738. * This array holds the node attributes of this builder
  29739. * created via {@link BufferAttributeNode}.
  29740. *
  29741. * @type {Array<NodeAttribute>}
  29742. */
  29743. this.bufferAttributes = [];
  29744. /**
  29745. * This array holds the node varyings of this builder.
  29746. *
  29747. * @type {Array<NodeVarying>}
  29748. */
  29749. this.varyings = [];
  29750. /**
  29751. * This dictionary holds the (native) node codes of this builder.
  29752. * The codes are maintained in an array for each shader stage.
  29753. *
  29754. * @type {Object<String,Array<NodeCode>>}
  29755. */
  29756. this.codes = {};
  29757. /**
  29758. * This dictionary holds the node variables of this builder.
  29759. * The variables are maintained in an array for each shader stage.
  29760. *
  29761. * @type {Object<String,Array<NodeVar>>}
  29762. */
  29763. this.vars = {};
  29764. /**
  29765. * Current code flow.
  29766. * All code generated in this stack will be stored in `.flow`.
  29767. *
  29768. * @type {{code: String}}
  29769. */
  29770. this.flow = { code: '' };
  29771. /**
  29772. * A chain of nodes.
  29773. * Used to check recursive calls in node-graph.
  29774. *
  29775. * @type {Array<Node>}
  29776. */
  29777. this.chaining = [];
  29778. /**
  29779. * The current stack.
  29780. * This reflects the current process in the code block hierarchy,
  29781. * it is useful to know if the current process is inside a conditional for example.
  29782. *
  29783. * @type {StackNode}
  29784. */
  29785. this.stack = stack();
  29786. /**
  29787. * List of stack nodes.
  29788. * The current stack hierarchy is stored in an array.
  29789. *
  29790. * @type {Array<StackNode>}
  29791. */
  29792. this.stacks = [];
  29793. /**
  29794. * A tab value. Used for shader string generation.
  29795. *
  29796. * @type {String}
  29797. * @default '\t'
  29798. */
  29799. this.tab = '\t';
  29800. /**
  29801. * Reference to the current function node.
  29802. *
  29803. * @type {FunctionNode?}
  29804. * @default null
  29805. */
  29806. this.currentFunctionNode = null;
  29807. /**
  29808. * The builder's context.
  29809. *
  29810. * @type {Object}
  29811. */
  29812. this.context = {
  29813. material: this.material
  29814. };
  29815. /**
  29816. * The builder's cache.
  29817. *
  29818. * @type {NodeCache}
  29819. */
  29820. this.cache = new NodeCache();
  29821. /**
  29822. * Since the {@link NodeBuilder#cache} might be temporarily
  29823. * overwritten by other caches, this member retains the reference
  29824. * to the builder's own cache.
  29825. *
  29826. * @type {NodeCache}
  29827. * @default this.cache
  29828. */
  29829. this.globalCache = this.cache;
  29830. this.flowsData = new WeakMap();
  29831. /**
  29832. * The current shader stage.
  29833. *
  29834. * @type {('vertex'|'fragment'|'compute'|'any')?}
  29835. */
  29836. this.shaderStage = null;
  29837. /**
  29838. * The current build stage.
  29839. *
  29840. * @type {('setup'|'analyze'|'generate')?}
  29841. */
  29842. this.buildStage = null;
  29843. /**
  29844. * Whether comparison in shader code are generated with methods or not.
  29845. *
  29846. * @type {Boolean}
  29847. * @default false
  29848. */
  29849. this.useComparisonMethod = false;
  29850. }
  29851. /**
  29852. * Returns the bind groups of the current renderer.
  29853. *
  29854. * @return {ChainMap} The cache.
  29855. */
  29856. getBindGroupsCache() {
  29857. let bindGroupsCache = rendererCache.get( this.renderer );
  29858. if ( bindGroupsCache === undefined ) {
  29859. bindGroupsCache = new ChainMap();
  29860. rendererCache.set( this.renderer, bindGroupsCache );
  29861. }
  29862. return bindGroupsCache;
  29863. }
  29864. /**
  29865. * Factory method for creating an instance of {@link RenderTarget} with the given
  29866. * dimensions and options.
  29867. *
  29868. * @param {Number} width - The width of the render target.
  29869. * @param {Number} height - The height of the render target.
  29870. * @param {Object} options - The options of the render target.
  29871. * @return {RenderTarget} The render target.
  29872. */
  29873. createRenderTarget( width, height, options ) {
  29874. return new RenderTarget( width, height, options );
  29875. }
  29876. /**
  29877. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  29878. * dimensions and options.
  29879. *
  29880. * @param {Number} size - The size of the cube render target.
  29881. * @param {Object} options - The options of the cube render target.
  29882. * @return {CubeRenderTarget} The cube render target.
  29883. */
  29884. createCubeRenderTarget( size, options ) {
  29885. return new CubeRenderTarget( size, options );
  29886. }
  29887. /**
  29888. * Factory method for creating an instance of {@link PMREMGenerator}.
  29889. *
  29890. * @return {PMREMGenerator} The PMREM generator.
  29891. */
  29892. createPMREMGenerator() {
  29893. // TODO: Move Materials.js to outside of the Nodes.js in order to remove this function and improve tree-shaking support
  29894. return new PMREMGenerator( this.renderer );
  29895. }
  29896. /**
  29897. * Whether the given node is included in the internal array of nodes or not.
  29898. *
  29899. * @param {Node} node - The node to test.
  29900. * @return {Boolean} Whether the given node is included in the internal array of nodes or not.
  29901. */
  29902. includes( node ) {
  29903. return this.nodes.includes( node );
  29904. }
  29905. /**
  29906. * Returns the output struct name which is required by
  29907. * {@link module:OutputStructNode}.
  29908. *
  29909. * @abstract
  29910. * @return {String} The name of the output struct.
  29911. */
  29912. getOutputStructName() {}
  29913. /**
  29914. * Returns a bind group for the given group name and binding.
  29915. *
  29916. * @private
  29917. * @param {String} groupName - The group name.
  29918. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  29919. * @return {BindGroup} The bind group
  29920. */
  29921. _getBindGroup( groupName, bindings ) {
  29922. const bindGroupsCache = this.getBindGroupsCache();
  29923. //
  29924. const bindingsArray = [];
  29925. let sharedGroup = true;
  29926. for ( const binding of bindings ) {
  29927. bindingsArray.push( binding );
  29928. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  29929. }
  29930. //
  29931. let bindGroup;
  29932. if ( sharedGroup ) {
  29933. bindGroup = bindGroupsCache.get( bindingsArray );
  29934. if ( bindGroup === undefined ) {
  29935. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29936. bindGroupsCache.set( bindingsArray, bindGroup );
  29937. }
  29938. } else {
  29939. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  29940. }
  29941. return bindGroup;
  29942. }
  29943. /**
  29944. * Returns an array of node uniform groups for the given group name and shader stage.
  29945. *
  29946. * @param {String} groupName - The group name.
  29947. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  29948. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  29949. */
  29950. getBindGroupArray( groupName, shaderStage ) {
  29951. const bindings = this.bindings[ shaderStage ];
  29952. let bindGroup = bindings[ groupName ];
  29953. if ( bindGroup === undefined ) {
  29954. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  29955. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  29956. }
  29957. bindings[ groupName ] = bindGroup = [];
  29958. }
  29959. return bindGroup;
  29960. }
  29961. /**
  29962. * Returns a list bindings of all shader stages separated by groups.
  29963. *
  29964. * @return {Array<BindGroup>} The list of bindings.
  29965. */
  29966. getBindings() {
  29967. let bindingsGroups = this.bindGroups;
  29968. if ( bindingsGroups === null ) {
  29969. const groups = {};
  29970. const bindings = this.bindings;
  29971. for ( const shaderStage of shaderStages ) {
  29972. for ( const groupName in bindings[ shaderStage ] ) {
  29973. const uniforms = bindings[ shaderStage ][ groupName ];
  29974. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  29975. groupUniforms.push( ...uniforms );
  29976. }
  29977. }
  29978. bindingsGroups = [];
  29979. for ( const groupName in groups ) {
  29980. const group = groups[ groupName ];
  29981. const bindingsGroup = this._getBindGroup( groupName, group );
  29982. bindingsGroups.push( bindingsGroup );
  29983. }
  29984. this.bindGroups = bindingsGroups;
  29985. }
  29986. return bindingsGroups;
  29987. }
  29988. /**
  29989. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  29990. */
  29991. sortBindingGroups() {
  29992. const bindingsGroups = this.getBindings();
  29993. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  29994. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  29995. const bindingGroup = bindingsGroups[ i ];
  29996. this.bindingsIndexes[ bindingGroup.name ].group = i;
  29997. bindingGroup.index = i;
  29998. }
  29999. }
  30000. /**
  30001. * The builder maintains each node in a hash-based dictionary.
  30002. * This method sets the given node (value) with the given hash (key) into this dictionary.
  30003. *
  30004. * @param {Node} node - The node to add.
  30005. * @param {Number} hash - The hash of the node.
  30006. */
  30007. setHashNode( node, hash ) {
  30008. this.hashNodes[ hash ] = node;
  30009. }
  30010. /**
  30011. * Adds a node to this builder.
  30012. *
  30013. * @param {Node} node - The node to add.
  30014. */
  30015. addNode( node ) {
  30016. if ( this.nodes.includes( node ) === false ) {
  30017. this.nodes.push( node );
  30018. this.setHashNode( node, node.getHash( this ) );
  30019. }
  30020. }
  30021. /**
  30022. * It is used to add Nodes that will be used as FRAME and RENDER events,
  30023. * and need to follow a certain sequence in the calls to work correctly.
  30024. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  30025. *
  30026. * @param {Node} node - The node to add.
  30027. */
  30028. addSequentialNode( node ) {
  30029. if ( this.sequentialNodes.includes( node ) === false ) {
  30030. this.sequentialNodes.push( node );
  30031. }
  30032. }
  30033. /**
  30034. * Checks the update types of nodes
  30035. */
  30036. buildUpdateNodes() {
  30037. for ( const node of this.nodes ) {
  30038. const updateType = node.getUpdateType();
  30039. if ( updateType !== NodeUpdateType.NONE ) {
  30040. this.updateNodes.push( node.getSelf() );
  30041. }
  30042. }
  30043. for ( const node of this.sequentialNodes ) {
  30044. const updateBeforeType = node.getUpdateBeforeType();
  30045. const updateAfterType = node.getUpdateAfterType();
  30046. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  30047. this.updateBeforeNodes.push( node.getSelf() );
  30048. }
  30049. if ( updateAfterType !== NodeUpdateType.NONE ) {
  30050. this.updateAfterNodes.push( node.getSelf() );
  30051. }
  30052. }
  30053. }
  30054. /**
  30055. * A reference the current node which is the
  30056. * last node in the chain of nodes.
  30057. *
  30058. * @type {Node}
  30059. */
  30060. get currentNode() {
  30061. return this.chaining[ this.chaining.length - 1 ];
  30062. }
  30063. /**
  30064. * Whether the given texture is filtered or not.
  30065. *
  30066. * @param {Texture} texture - The texture to check.
  30067. * @return {Boolean} Whether the given texture is filtered or not.
  30068. */
  30069. isFilteredTexture( texture ) {
  30070. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  30071. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  30072. }
  30073. /**
  30074. * Adds the given node to the internal node chain.
  30075. * This is used to check recursive calls in node-graph.
  30076. *
  30077. * @param {Node} node - The node to add.
  30078. */
  30079. addChain( node ) {
  30080. /*
  30081. if ( this.chaining.indexOf( node ) !== - 1 ) {
  30082. console.warn( 'Recursive node: ', node );
  30083. }
  30084. */
  30085. this.chaining.push( node );
  30086. }
  30087. /**
  30088. * Removes the given node from the internal node chain.
  30089. *
  30090. * @param {Node} node - The node to remove.
  30091. */
  30092. removeChain( node ) {
  30093. const lastChain = this.chaining.pop();
  30094. if ( lastChain !== node ) {
  30095. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  30096. }
  30097. }
  30098. /**
  30099. * Returns the native shader method name for a given generic name. E.g.
  30100. * the method name `textureDimensions` matches the WGSL name but must be
  30101. * resolved to `textureSize` in GLSL.
  30102. *
  30103. * @abstract
  30104. * @param {String} method - The method name to resolve.
  30105. * @return {String} The resolved method name.
  30106. */
  30107. getMethod( method ) {
  30108. return method;
  30109. }
  30110. /**
  30111. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  30112. *
  30113. * @param {Number} hash - The hash of the node.
  30114. * @return {Node} The found node.
  30115. */
  30116. getNodeFromHash( hash ) {
  30117. return this.hashNodes[ hash ];
  30118. }
  30119. /**
  30120. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  30121. *
  30122. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  30123. * @param {Node} node - The node to add.
  30124. * @return {Node} The node.
  30125. */
  30126. addFlow( shaderStage, node ) {
  30127. this.flowNodes[ shaderStage ].push( node );
  30128. return node;
  30129. }
  30130. /**
  30131. * Sets builder's context.
  30132. *
  30133. * @param {Object} context - The context to set.
  30134. */
  30135. setContext( context ) {
  30136. this.context = context;
  30137. }
  30138. /**
  30139. * Returns the builder's current context.
  30140. *
  30141. * @return {Object} The builder's current context.
  30142. */
  30143. getContext() {
  30144. return this.context;
  30145. }
  30146. /**
  30147. * Gets a context used in shader construction that can be shared across different materials.
  30148. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  30149. *
  30150. * @return {Object} The builder's current context without material.
  30151. */
  30152. getSharedContext() {
  30153. ({ ...this.context });
  30154. return this.context;
  30155. }
  30156. /**
  30157. * Sets builder's cache.
  30158. *
  30159. * @param {NodeCache} cache - The cache to set.
  30160. */
  30161. setCache( cache ) {
  30162. this.cache = cache;
  30163. }
  30164. /**
  30165. * Returns the builder's current cache.
  30166. *
  30167. * @return {NodeCache} The builder's current cache.
  30168. */
  30169. getCache() {
  30170. return this.cache;
  30171. }
  30172. /**
  30173. * Returns a cache for the given node.
  30174. *
  30175. * @param {Node} node - The node.
  30176. * @param {Boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  30177. * @return {NodeCache} The cache.
  30178. */
  30179. getCacheFromNode( node, parent = true ) {
  30180. const data = this.getDataFromNode( node );
  30181. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  30182. return data.cache;
  30183. }
  30184. /**
  30185. * Whether the requested feature is available or not.
  30186. *
  30187. * @abstract
  30188. * @param {String} name - The requested feature.
  30189. * @return {Boolean} Whether the requested feature is supported or not.
  30190. */
  30191. isAvailable( /*name*/ ) {
  30192. return false;
  30193. }
  30194. /**
  30195. * Returns the vertexIndex input variable as a native shader string.
  30196. *
  30197. * @abstract
  30198. * @return {String} The instanceIndex shader string.
  30199. */
  30200. getVertexIndex() {
  30201. console.warn( 'Abstract function.' );
  30202. }
  30203. /**
  30204. * Returns the instanceIndex input variable as a native shader string.
  30205. *
  30206. * @abstract
  30207. * @return {String} The instanceIndex shader string.
  30208. */
  30209. getInstanceIndex() {
  30210. console.warn( 'Abstract function.' );
  30211. }
  30212. /**
  30213. * Returns the drawIndex input variable as a native shader string.
  30214. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  30215. *
  30216. * @abstract
  30217. * @return {String} The drawIndex shader string.
  30218. */
  30219. getDrawIndex() {
  30220. console.warn( 'Abstract function.' );
  30221. }
  30222. /**
  30223. * Returns the frontFacing input variable as a native shader string.
  30224. *
  30225. * @abstract
  30226. * @return {String} The frontFacing shader string.
  30227. */
  30228. getFrontFacing() {
  30229. console.warn( 'Abstract function.' );
  30230. }
  30231. /**
  30232. * Returns the fragCoord input variable as a native shader string.
  30233. *
  30234. * @abstract
  30235. * @return {String} The fragCoord shader string.
  30236. */
  30237. getFragCoord() {
  30238. console.warn( 'Abstract function.' );
  30239. }
  30240. /**
  30241. * Whether to flip texture data along its vertical axis or not. WebGL needs
  30242. * this method evaluate to `true`, WebGPU to `false`.
  30243. *
  30244. * @abstract
  30245. * @return {Boolean} Whether to flip texture data along its vertical axis or not.
  30246. */
  30247. isFlipY() {
  30248. return false;
  30249. }
  30250. /**
  30251. * Calling this method increases the usage count for the given node by one.
  30252. *
  30253. * @param {Node} node - The node to increase the usage count for.
  30254. * @return {Number} The updated usage count.
  30255. */
  30256. increaseUsage( node ) {
  30257. const nodeData = this.getDataFromNode( node );
  30258. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  30259. return nodeData.usageCount;
  30260. }
  30261. /**
  30262. * Generates a texture sample shader string for the given texture data.
  30263. *
  30264. * @abstract
  30265. * @param {Texture} texture - The texture.
  30266. * @param {String} textureProperty - The texture property name.
  30267. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30268. * @return {String} The generated shader string.
  30269. */
  30270. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  30271. console.warn( 'Abstract function.' );
  30272. }
  30273. /**
  30274. * Generates a texture LOD shader string for the given texture data.
  30275. *
  30276. * @abstract
  30277. * @param {Texture} texture - The texture.
  30278. * @param {String} textureProperty - The texture property name.
  30279. * @param {String} uvSnippet - Snippet defining the texture coordinates.
  30280. * @param {String?} depthSnippet - Snippet defining the 0-based texture array index to sample.
  30281. * @param {String} levelSnippet - Snippet defining the mip level.
  30282. * @return {String} The generated shader string.
  30283. */
  30284. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  30285. console.warn( 'Abstract function.' );
  30286. }
  30287. /**
  30288. * Generates the shader string for the given type and value.
  30289. *
  30290. * @param {String} type - The type.
  30291. * @param {Any?} [value=null] - The value.
  30292. * @return {String} The generated value as a shader string.
  30293. */
  30294. generateConst( type, value = null ) {
  30295. if ( value === null ) {
  30296. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  30297. else if ( type === 'bool' ) value = false;
  30298. else if ( type === 'color' ) value = new Color();
  30299. else if ( type === 'vec2' ) value = new Vector2();
  30300. else if ( type === 'vec3' ) value = new Vector3();
  30301. else if ( type === 'vec4' ) value = new Vector4();
  30302. }
  30303. if ( type === 'float' ) return toFloat( value );
  30304. if ( type === 'int' ) return `${ Math.round( value ) }`;
  30305. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  30306. if ( type === 'bool' ) return value ? 'true' : 'false';
  30307. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  30308. const typeLength = this.getTypeLength( type );
  30309. const componentType = this.getComponentType( type );
  30310. const generateConst = value => this.generateConst( componentType, value );
  30311. if ( typeLength === 2 ) {
  30312. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  30313. } else if ( typeLength === 3 ) {
  30314. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  30315. } else if ( typeLength === 4 ) {
  30316. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  30317. } else if ( typeLength > 4 && value && ( value.isMatrix3 || value.isMatrix4 ) ) {
  30318. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  30319. } else if ( typeLength > 4 ) {
  30320. return `${ this.getType( type ) }()`;
  30321. }
  30322. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  30323. }
  30324. /**
  30325. * It might be necessary to convert certain data types to different ones
  30326. * so this method can be used to hide the conversion.
  30327. *
  30328. * @param {String} type - The type.
  30329. * @return {String} The updated type.
  30330. */
  30331. getType( type ) {
  30332. if ( type === 'color' ) return 'vec3';
  30333. return type;
  30334. }
  30335. /**
  30336. * Whether the given attribute name is defined in the geometry or not.
  30337. *
  30338. * @param {String} name - The attribute name.
  30339. * @return {Boolean} Whether the given attribute name is defined in the geometry.
  30340. */
  30341. hasGeometryAttribute( name ) {
  30342. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  30343. }
  30344. /**
  30345. * Returns a node attribute for the given name and type.
  30346. *
  30347. * @param {String} name - The attribute's name.
  30348. * @param {String} type - The attribute's type.
  30349. * @return {NodeAttribute} The node attribute.
  30350. */
  30351. getAttribute( name, type ) {
  30352. const attributes = this.attributes;
  30353. // find attribute
  30354. for ( const attribute of attributes ) {
  30355. if ( attribute.name === name ) {
  30356. return attribute;
  30357. }
  30358. }
  30359. // create a new if no exist
  30360. const attribute = new NodeAttribute( name, type );
  30361. attributes.push( attribute );
  30362. return attribute;
  30363. }
  30364. /**
  30365. * Returns for the given node and shader stage the property name for the shader.
  30366. *
  30367. * @param {Node} node - The node.
  30368. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30369. * @return {String} The property name.
  30370. */
  30371. getPropertyName( node/*, shaderStage*/ ) {
  30372. return node.name;
  30373. }
  30374. /**
  30375. * Whether the given type is a vector type or not.
  30376. *
  30377. * @param {String} type - The type to check.
  30378. * @return {Boolean} Whether the given type is a vector type or not.
  30379. */
  30380. isVector( type ) {
  30381. return /vec\d/.test( type );
  30382. }
  30383. /**
  30384. * Whether the given type is a matrix type or not.
  30385. *
  30386. * @param {String} type - The type to check.
  30387. * @return {Boolean} Whether the given type is a matrix type or not.
  30388. */
  30389. isMatrix( type ) {
  30390. return /mat\d/.test( type );
  30391. }
  30392. /**
  30393. * Whether the given type is a reference type or not.
  30394. *
  30395. * @param {String} type - The type to check.
  30396. * @return {Boolean} Whether the given type is a reference type or not.
  30397. */
  30398. isReference( type ) {
  30399. return type === 'void' || type === 'property' || type === 'sampler' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  30400. }
  30401. /**
  30402. * Checks if the given texture requires a manual conversion to the working color space.
  30403. *
  30404. * @abstract
  30405. * @param {Texture} texture - The texture to check.
  30406. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  30407. */
  30408. needsToWorkingColorSpace( /*texture*/ ) {
  30409. return false;
  30410. }
  30411. /**
  30412. * Returns the component type of a given texture.
  30413. *
  30414. * @param {Texture} texture - The texture.
  30415. * @return {String} The component type.
  30416. */
  30417. getComponentTypeFromTexture( texture ) {
  30418. const type = texture.type;
  30419. if ( texture.isDataTexture ) {
  30420. if ( type === IntType ) return 'int';
  30421. if ( type === UnsignedIntType ) return 'uint';
  30422. }
  30423. return 'float';
  30424. }
  30425. /**
  30426. * Returns the element type for a given type.
  30427. *
  30428. * @param {String} type - The type.
  30429. * @return {String} The element type.
  30430. */
  30431. getElementType( type ) {
  30432. if ( type === 'mat2' ) return 'vec2';
  30433. if ( type === 'mat3' ) return 'vec3';
  30434. if ( type === 'mat4' ) return 'vec4';
  30435. return this.getComponentType( type );
  30436. }
  30437. /**
  30438. * Returns the component type for a given type.
  30439. *
  30440. * @param {String} type - The type.
  30441. * @return {String} The component type.
  30442. */
  30443. getComponentType( type ) {
  30444. type = this.getVectorType( type );
  30445. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  30446. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  30447. if ( componentType === null ) return null;
  30448. if ( componentType[ 1 ] === 'b' ) return 'bool';
  30449. if ( componentType[ 1 ] === 'i' ) return 'int';
  30450. if ( componentType[ 1 ] === 'u' ) return 'uint';
  30451. return 'float';
  30452. }
  30453. /**
  30454. * Returns the vector type for a given type.
  30455. *
  30456. * @param {String} type - The type.
  30457. * @return {String} The vector type.
  30458. */
  30459. getVectorType( type ) {
  30460. if ( type === 'color' ) return 'vec3';
  30461. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  30462. return type;
  30463. }
  30464. /**
  30465. * Returns the data type for the given the length and component type.
  30466. *
  30467. * @param {Number} length - The length.
  30468. * @param {String} [componentType='float'] - The component type.
  30469. * @return {String} The type.
  30470. */
  30471. getTypeFromLength( length, componentType = 'float' ) {
  30472. if ( length === 1 ) return componentType;
  30473. const baseType = getTypeFromLength( length );
  30474. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  30475. return prefix + baseType;
  30476. }
  30477. /**
  30478. * Returns the type for a given typed array.
  30479. *
  30480. * @param {TypedArray} array - The typed array.
  30481. * @return {String} The type.
  30482. */
  30483. getTypeFromArray( array ) {
  30484. return typeFromArray.get( array.constructor );
  30485. }
  30486. /**
  30487. * Returns the type for a given buffer attribute.
  30488. *
  30489. * @param {BufferAttribute} attribute - The buffer attribute.
  30490. * @return {String} The type.
  30491. */
  30492. getTypeFromAttribute( attribute ) {
  30493. let dataAttribute = attribute;
  30494. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  30495. const array = dataAttribute.array;
  30496. const itemSize = attribute.itemSize;
  30497. const normalized = attribute.normalized;
  30498. let arrayType;
  30499. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  30500. arrayType = this.getTypeFromArray( array );
  30501. }
  30502. return this.getTypeFromLength( itemSize, arrayType );
  30503. }
  30504. /**
  30505. * Returns the length for the given data type.
  30506. *
  30507. * @param {String} type - The data type.
  30508. * @return {Number} The length.
  30509. */
  30510. getTypeLength( type ) {
  30511. const vecType = this.getVectorType( type );
  30512. const vecNum = /vec([2-4])/.exec( vecType );
  30513. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  30514. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  30515. if ( /mat2/.test( type ) === true ) return 4;
  30516. if ( /mat3/.test( type ) === true ) return 9;
  30517. if ( /mat4/.test( type ) === true ) return 16;
  30518. return 0;
  30519. }
  30520. /**
  30521. * Returns the vector type for a given matrix type.
  30522. *
  30523. * @param {String} type - The matrix type.
  30524. * @return {String} The vector type.
  30525. */
  30526. getVectorFromMatrix( type ) {
  30527. return type.replace( 'mat', 'vec' );
  30528. }
  30529. /**
  30530. * For a given type this method changes the component type to the
  30531. * given value. E.g. `vec4` should be changed to the new component type
  30532. * `uint` which results in `uvec4`.
  30533. *
  30534. * @param {String} type - The type.
  30535. * @param {String} newComponentType - The new component type.
  30536. * @return {String} The new type.
  30537. */
  30538. changeComponentType( type, newComponentType ) {
  30539. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  30540. }
  30541. /**
  30542. * Returns the integer type pendant for the given type.
  30543. *
  30544. * @param {String} type - The type.
  30545. * @return {String} The integer type.
  30546. */
  30547. getIntegerType( type ) {
  30548. const componentType = this.getComponentType( type );
  30549. if ( componentType === 'int' || componentType === 'uint' ) return type;
  30550. return this.changeComponentType( type, 'int' );
  30551. }
  30552. /**
  30553. * Adds a stack node to the internal stack.
  30554. *
  30555. * @return {StackNode} The added stack node.
  30556. */
  30557. addStack() {
  30558. this.stack = stack( this.stack );
  30559. this.stacks.push( getCurrentStack() || this.stack );
  30560. setCurrentStack( this.stack );
  30561. return this.stack;
  30562. }
  30563. /**
  30564. * Removes the last stack node from the internal stack.
  30565. *
  30566. * @return {StackNode} The removed stack node.
  30567. */
  30568. removeStack() {
  30569. const lastStack = this.stack;
  30570. this.stack = lastStack.parent;
  30571. setCurrentStack( this.stacks.pop() );
  30572. return lastStack;
  30573. }
  30574. /**
  30575. * The builder maintains (cached) data for each node during the building process. This method
  30576. * can be used to get these data for a specific shader stage and cache.
  30577. *
  30578. * @param {Node} node - The node to get the data for.
  30579. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30580. * @param {NodeCache?} cache - An optional cache.
  30581. * @return {Object} The node data.
  30582. */
  30583. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  30584. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  30585. let nodeData = cache.getData( node );
  30586. if ( nodeData === undefined ) {
  30587. nodeData = {};
  30588. cache.setData( node, nodeData );
  30589. }
  30590. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  30591. return nodeData[ shaderStage ];
  30592. }
  30593. /**
  30594. * Returns the properties for the given node and shader stage.
  30595. *
  30596. * @param {Node} node - The node to get the properties for.
  30597. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  30598. * @return {Object} The node properties.
  30599. */
  30600. getNodeProperties( node, shaderStage = 'any' ) {
  30601. const nodeData = this.getDataFromNode( node, shaderStage );
  30602. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  30603. }
  30604. /**
  30605. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  30606. *
  30607. * @param {BufferAttributeNode} node - The buffer attribute node.
  30608. * @param {String} type - The node type.
  30609. * @return {NodeAttribute} The node attribute.
  30610. */
  30611. getBufferAttributeFromNode( node, type ) {
  30612. const nodeData = this.getDataFromNode( node );
  30613. let bufferAttribute = nodeData.bufferAttribute;
  30614. if ( bufferAttribute === undefined ) {
  30615. const index = this.uniforms.index ++;
  30616. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  30617. this.bufferAttributes.push( bufferAttribute );
  30618. nodeData.bufferAttribute = bufferAttribute;
  30619. }
  30620. return bufferAttribute;
  30621. }
  30622. /**
  30623. * Returns an instance of {@link StructTypeNode} for the given output struct node.
  30624. *
  30625. * @param {OutputStructNode} node - The output struct node.
  30626. * @param {Array<String>} types - The output struct types.
  30627. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30628. * @return {StructTypeNode} The struct type attribute.
  30629. */
  30630. getStructTypeFromNode( node, types, shaderStage = this.shaderStage ) {
  30631. const nodeData = this.getDataFromNode( node, shaderStage );
  30632. let structType = nodeData.structType;
  30633. if ( structType === undefined ) {
  30634. const index = this.structs.index ++;
  30635. structType = new StructTypeNode( 'StructType' + index, types );
  30636. this.structs[ shaderStage ].push( structType );
  30637. nodeData.structType = structType;
  30638. }
  30639. return structType;
  30640. }
  30641. /**
  30642. * Returns an instance of {@link NodeUniform} for the given uniform node.
  30643. *
  30644. * @param {UniformNode} node - The uniform node.
  30645. * @param {String} type - The uniform type.
  30646. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30647. * @param {String?} name - The name of the uniform.
  30648. * @return {NodeUniform} The node uniform.
  30649. */
  30650. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  30651. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  30652. let nodeUniform = nodeData.uniform;
  30653. if ( nodeUniform === undefined ) {
  30654. const index = this.uniforms.index ++;
  30655. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  30656. this.uniforms[ shaderStage ].push( nodeUniform );
  30657. nodeData.uniform = nodeUniform;
  30658. }
  30659. return nodeUniform;
  30660. }
  30661. /**
  30662. * Returns an instance of {@link NodeVar} for the given variable node.
  30663. *
  30664. * @param {VarNode} node - The variable node.
  30665. * @param {String?} name - The variable's name.
  30666. * @param {String} [type=node.getNodeType( this )] - The variable's type.
  30667. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30668. * @param {Boolean} [readOnly=false] - Whether the variable is read-only or not.
  30669. *
  30670. * @return {NodeVar} The node variable.
  30671. */
  30672. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  30673. const nodeData = this.getDataFromNode( node, shaderStage );
  30674. let nodeVar = nodeData.variable;
  30675. if ( nodeVar === undefined ) {
  30676. const idNS = readOnly ? '_const' : '_var';
  30677. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  30678. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  30679. if ( name === null ) {
  30680. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  30681. this.vars[ idNS ] ++;
  30682. }
  30683. nodeVar = new NodeVar( name, type, readOnly );
  30684. if ( ! readOnly ) {
  30685. vars.push( nodeVar );
  30686. }
  30687. nodeData.variable = nodeVar;
  30688. }
  30689. return nodeVar;
  30690. }
  30691. /**
  30692. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  30693. *
  30694. * @param {Node} node - The varying node.
  30695. * @return {Boolean} Returns true if deterministic.
  30696. */
  30697. isDeterministic( node ) {
  30698. if ( node.isMathNode ) {
  30699. return this.isDeterministic( node.aNode ) &&
  30700. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  30701. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  30702. } else if ( node.isOperatorNode ) {
  30703. return this.isDeterministic( node.aNode ) &&
  30704. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  30705. } else if ( node.isConstNode ) {
  30706. return true;
  30707. }
  30708. return false;
  30709. }
  30710. /**
  30711. * Returns an instance of {@link NodeVarying} for the given varying node.
  30712. *
  30713. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  30714. * @param {String?} name - The varying's name.
  30715. * @param {String} [type=node.getNodeType( this )] - The varying's type.
  30716. * @return {NodeVar} The node varying.
  30717. */
  30718. getVaryingFromNode( node, name = null, type = node.getNodeType( this ) ) {
  30719. const nodeData = this.getDataFromNode( node, 'any' );
  30720. let nodeVarying = nodeData.varying;
  30721. if ( nodeVarying === undefined ) {
  30722. const varyings = this.varyings;
  30723. const index = varyings.length;
  30724. if ( name === null ) name = 'nodeVarying' + index;
  30725. nodeVarying = new NodeVarying( name, type );
  30726. varyings.push( nodeVarying );
  30727. nodeData.varying = nodeVarying;
  30728. }
  30729. return nodeVarying;
  30730. }
  30731. /**
  30732. * Returns an instance of {@link NodeCode} for the given code node.
  30733. *
  30734. * @param {CodeNode} node - The code node.
  30735. * @param {String} type - The node type.
  30736. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  30737. * @return {NodeCode} The node code.
  30738. */
  30739. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  30740. const nodeData = this.getDataFromNode( node );
  30741. let nodeCode = nodeData.code;
  30742. if ( nodeCode === undefined ) {
  30743. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  30744. const index = codes.length;
  30745. nodeCode = new NodeCode( 'nodeCode' + index, type );
  30746. codes.push( nodeCode );
  30747. nodeData.code = nodeCode;
  30748. }
  30749. return nodeCode;
  30750. }
  30751. /**
  30752. * Adds a code flow based on the code-block hierarchy.
  30753. * This is used so that code-blocks like If,Else create their variables locally if the Node
  30754. * is only used inside one of these conditionals in the current shader stage.
  30755. *
  30756. * @param {Node} node - The node to add.
  30757. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  30758. */
  30759. addFlowCodeHierarchy( node, nodeBlock ) {
  30760. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  30761. let needsFlowCode = true;
  30762. let nodeBlockHierarchy = nodeBlock;
  30763. while ( nodeBlockHierarchy ) {
  30764. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  30765. needsFlowCode = false;
  30766. break;
  30767. }
  30768. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  30769. }
  30770. if ( needsFlowCode ) {
  30771. for ( const flowCode of flowCodes ) {
  30772. this.addLineFlowCode( flowCode );
  30773. }
  30774. }
  30775. }
  30776. /**
  30777. * Add a inline-code to the current flow code-block.
  30778. *
  30779. * @param {Node} node - The node to add.
  30780. * @param {String} code - The code to add.
  30781. * @param {Node} nodeBlock - Current ConditionalNode
  30782. */
  30783. addLineFlowCodeBlock( node, code, nodeBlock ) {
  30784. const nodeData = this.getDataFromNode( node );
  30785. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  30786. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  30787. flowCodes.push( code );
  30788. codeBlock.set( nodeBlock, true );
  30789. }
  30790. /**
  30791. * Add a inline-code to the current flow.
  30792. *
  30793. * @param {String} code - The code to add.
  30794. * @param {Node?} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  30795. * @return {NodeBuilder} A reference to this node builder.
  30796. */
  30797. addLineFlowCode( code, node = null ) {
  30798. if ( code === '' ) return this;
  30799. if ( node !== null && this.context.nodeBlock ) {
  30800. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  30801. }
  30802. code = this.tab + code;
  30803. if ( ! /;\s*$/.test( code ) ) {
  30804. code = code + ';\n';
  30805. }
  30806. this.flow.code += code;
  30807. return this;
  30808. }
  30809. /**
  30810. * Adds a code to the current code flow.
  30811. *
  30812. * @param {String} code - Shader code.
  30813. * @return {NodeBuilder} A reference to this node builder.
  30814. */
  30815. addFlowCode( code ) {
  30816. this.flow.code += code;
  30817. return this;
  30818. }
  30819. /**
  30820. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  30821. * Typically used in codes with If,Else.
  30822. *
  30823. * @return {NodeBuilder} A reference to this node builder.
  30824. */
  30825. addFlowTab() {
  30826. this.tab += '\t';
  30827. return this;
  30828. }
  30829. /**
  30830. * Removes a tab.
  30831. *
  30832. * @return {NodeBuilder} A reference to this node builder.
  30833. */
  30834. removeFlowTab() {
  30835. this.tab = this.tab.slice( 0, - 1 );
  30836. return this;
  30837. }
  30838. /**
  30839. * Gets the current flow data based on a Node.
  30840. *
  30841. * @param {Node} node - Node that the flow was started.
  30842. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30843. * @return {Object} The flow data.
  30844. */
  30845. getFlowData( node/*, shaderStage*/ ) {
  30846. return this.flowsData.get( node );
  30847. }
  30848. /**
  30849. * Executes the node flow based on a root node to generate the final shader code.
  30850. *
  30851. * @param {Node} node - The node to execute.
  30852. * @return {Object} The code flow.
  30853. */
  30854. flowNode( node ) {
  30855. const output = node.getNodeType( this );
  30856. const flowData = this.flowChildNode( node, output );
  30857. this.flowsData.set( node, flowData );
  30858. return flowData;
  30859. }
  30860. /**
  30861. * Returns the native shader operator name for a given generic name.
  30862. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30863. *
  30864. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  30865. * @return {FunctionNode} The build function node.
  30866. */
  30867. buildFunctionNode( shaderNode ) {
  30868. const fn = new FunctionNode();
  30869. const previous = this.currentFunctionNode;
  30870. this.currentFunctionNode = fn;
  30871. fn.code = this.buildFunctionCode( shaderNode );
  30872. this.currentFunctionNode = previous;
  30873. return fn;
  30874. }
  30875. /**
  30876. * Generates a code flow based on a TSL function: Fn().
  30877. *
  30878. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  30879. * @return {Object}
  30880. */
  30881. flowShaderNode( shaderNode ) {
  30882. const layout = shaderNode.layout;
  30883. const inputs = {
  30884. [ Symbol.iterator ]() {
  30885. let index = 0;
  30886. const values = Object.values( this );
  30887. return {
  30888. next: () => ( {
  30889. value: values[ index ],
  30890. done: index ++ >= values.length
  30891. } )
  30892. };
  30893. }
  30894. };
  30895. for ( const input of layout.inputs ) {
  30896. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  30897. }
  30898. //
  30899. shaderNode.layout = null;
  30900. const callNode = shaderNode.call( inputs );
  30901. const flowData = this.flowStagesNode( callNode, layout.type );
  30902. shaderNode.layout = layout;
  30903. return flowData;
  30904. }
  30905. /**
  30906. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  30907. *
  30908. * @param {Node} node - The node to execute.
  30909. * @param {String?} output - Expected output type. For example 'vec3'.
  30910. * @return {Object}
  30911. */
  30912. flowStagesNode( node, output = null ) {
  30913. const previousFlow = this.flow;
  30914. const previousVars = this.vars;
  30915. const previousCache = this.cache;
  30916. const previousBuildStage = this.buildStage;
  30917. const previousStack = this.stack;
  30918. const flow = {
  30919. code: ''
  30920. };
  30921. this.flow = flow;
  30922. this.vars = {};
  30923. this.cache = new NodeCache();
  30924. this.stack = stack();
  30925. for ( const buildStage of defaultBuildStages ) {
  30926. this.setBuildStage( buildStage );
  30927. flow.result = node.build( this, output );
  30928. }
  30929. flow.vars = this.getVars( this.shaderStage );
  30930. this.flow = previousFlow;
  30931. this.vars = previousVars;
  30932. this.cache = previousCache;
  30933. this.stack = previousStack;
  30934. this.setBuildStage( previousBuildStage );
  30935. return flow;
  30936. }
  30937. /**
  30938. * Returns the native shader operator name for a given generic name.
  30939. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  30940. *
  30941. * @abstract
  30942. * @param {String} op - The operator name to resolve.
  30943. * @return {String} The resolved operator name.
  30944. */
  30945. getFunctionOperator( /* op */ ) {
  30946. return null;
  30947. }
  30948. /**
  30949. * Generates a code flow based on a child Node.
  30950. *
  30951. * @param {Node} node - The node to execute.
  30952. * @param {String?} output - Expected output type. For example 'vec3'.
  30953. * @return {Object} The code flow.
  30954. */
  30955. flowChildNode( node, output = null ) {
  30956. const previousFlow = this.flow;
  30957. const flow = {
  30958. code: ''
  30959. };
  30960. this.flow = flow;
  30961. flow.result = node.build( this, output );
  30962. this.flow = previousFlow;
  30963. return flow;
  30964. }
  30965. /**
  30966. * Executes a flow of code in a different stage.
  30967. *
  30968. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  30969. * return the value in fragment-stage even if it is being executed in an input fragment.
  30970. *
  30971. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  30972. * @param {Node} node - The node to execute.
  30973. * @param {String?} output - Expected output type. For example 'vec3'.
  30974. * @param {String?} propertyName - The property name to assign the result.
  30975. * @return {Object}
  30976. */
  30977. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  30978. const previousShaderStage = this.shaderStage;
  30979. this.setShaderStage( shaderStage );
  30980. const flowData = this.flowChildNode( node, output );
  30981. if ( propertyName !== null ) {
  30982. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  30983. }
  30984. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  30985. this.setShaderStage( previousShaderStage );
  30986. return flowData;
  30987. }
  30988. /**
  30989. * Returns an array holding all node attributes of this node builder.
  30990. *
  30991. * @return {Array<NodeAttribute>} The node attributes of this builder.
  30992. */
  30993. getAttributesArray() {
  30994. return this.attributes.concat( this.bufferAttributes );
  30995. }
  30996. /**
  30997. * Returns the attribute definitions as a shader string for the given shader stage.
  30998. *
  30999. * @abstract
  31000. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31001. * @return {String} The attribute code section.
  31002. */
  31003. getAttributes( /*shaderStage*/ ) {
  31004. console.warn( 'Abstract function.' );
  31005. }
  31006. /**
  31007. * Returns the varying definitions as a shader string for the given shader stage.
  31008. *
  31009. * @abstract
  31010. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31011. * @return {String} The varying code section.
  31012. */
  31013. getVaryings( /*shaderStage*/ ) {
  31014. console.warn( 'Abstract function.' );
  31015. }
  31016. /**
  31017. * Returns a single variable definition as a shader string for the given variable type and name.
  31018. *
  31019. * @param {String} type - The variable's type.
  31020. * @param {String} name - The variable's name.
  31021. * @return {String} The shader string.
  31022. */
  31023. getVar( type, name ) {
  31024. return `${ this.getType( type ) } ${ name }`;
  31025. }
  31026. /**
  31027. * Returns the variable definitions as a shader string for the given shader stage.
  31028. *
  31029. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31030. * @return {String} The variable code section.
  31031. */
  31032. getVars( shaderStage ) {
  31033. let snippet = '';
  31034. const vars = this.vars[ shaderStage ];
  31035. if ( vars !== undefined ) {
  31036. for ( const variable of vars ) {
  31037. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  31038. }
  31039. }
  31040. return snippet;
  31041. }
  31042. /**
  31043. * Returns the uniform definitions as a shader string for the given shader stage.
  31044. *
  31045. * @abstract
  31046. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31047. * @return {String} The uniform code section.
  31048. */
  31049. getUniforms( /*shaderStage*/ ) {
  31050. console.warn( 'Abstract function.' );
  31051. }
  31052. /**
  31053. * Returns the native code definitions as a shader string for the given shader stage.
  31054. *
  31055. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  31056. * @return {String} The native code section.
  31057. */
  31058. getCodes( shaderStage ) {
  31059. const codes = this.codes[ shaderStage ];
  31060. let code = '';
  31061. if ( codes !== undefined ) {
  31062. for ( const nodeCode of codes ) {
  31063. code += nodeCode.code + '\n';
  31064. }
  31065. }
  31066. return code;
  31067. }
  31068. /**
  31069. * Returns the hash of this node builder.
  31070. *
  31071. * @return {String} The hash.
  31072. */
  31073. getHash() {
  31074. return this.vertexShader + this.fragmentShader + this.computeShader;
  31075. }
  31076. /**
  31077. * Sets the current shader stage.
  31078. *
  31079. * @param {('vertex'|'fragment'|'compute'|'any')?} shaderStage - The shader stage to set.
  31080. */
  31081. setShaderStage( shaderStage ) {
  31082. this.shaderStage = shaderStage;
  31083. }
  31084. /**
  31085. * Returns the current shader stage.
  31086. *
  31087. * @return {('vertex'|'fragment'|'compute'|'any')?} The current shader stage.
  31088. */
  31089. getShaderStage() {
  31090. return this.shaderStage;
  31091. }
  31092. /**
  31093. * Sets the current build stage.
  31094. *
  31095. * @param {('setup'|'analyze'|'generate')?} buildStage - The build stage to set.
  31096. */
  31097. setBuildStage( buildStage ) {
  31098. this.buildStage = buildStage;
  31099. }
  31100. /**
  31101. * Returns the current build stage.
  31102. *
  31103. * @return {('setup'|'analyze'|'generate')?} The current build stage.
  31104. */
  31105. getBuildStage() {
  31106. return this.buildStage;
  31107. }
  31108. /**
  31109. * Controls the code build of the shader stages.
  31110. *
  31111. * @abstract
  31112. */
  31113. buildCode() {
  31114. console.warn( 'Abstract function.' );
  31115. }
  31116. /**
  31117. * Central build method which controls the build for the given object.
  31118. *
  31119. * @return {NodeBuilder} A reference to this node builder.
  31120. */
  31121. build() {
  31122. const { object, material, renderer } = this;
  31123. if ( material !== null ) {
  31124. let nodeMaterial = renderer.library.fromMaterial( material );
  31125. if ( nodeMaterial === null ) {
  31126. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  31127. nodeMaterial = new NodeMaterial();
  31128. }
  31129. nodeMaterial.build( this );
  31130. } else {
  31131. this.addFlow( 'compute', object );
  31132. }
  31133. // setup() -> stage 1: create possible new nodes and returns an output reference node
  31134. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  31135. // generate() -> stage 3: generate shader
  31136. for ( const buildStage of defaultBuildStages ) {
  31137. this.setBuildStage( buildStage );
  31138. if ( this.context.vertex && this.context.vertex.isNode ) {
  31139. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  31140. }
  31141. for ( const shaderStage of shaderStages ) {
  31142. this.setShaderStage( shaderStage );
  31143. const flowNodes = this.flowNodes[ shaderStage ];
  31144. for ( const node of flowNodes ) {
  31145. if ( buildStage === 'generate' ) {
  31146. this.flowNode( node );
  31147. } else {
  31148. node.build( this );
  31149. }
  31150. }
  31151. }
  31152. }
  31153. this.setBuildStage( null );
  31154. this.setShaderStage( null );
  31155. // stage 4: build code for a specific output
  31156. this.buildCode();
  31157. this.buildUpdateNodes();
  31158. return this;
  31159. }
  31160. /**
  31161. * Returns a uniform representation which is later used for UBO generation and rendering.
  31162. *
  31163. * @param {NodeUniform} uniformNode - The uniform node.
  31164. * @param {String} type - The requested type.
  31165. * @return {Uniform} The uniform.
  31166. */
  31167. getNodeUniform( uniformNode, type ) {
  31168. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  31169. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  31170. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  31171. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  31172. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  31173. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  31174. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  31175. throw new Error( `Uniform "${type}" not declared.` );
  31176. }
  31177. /**
  31178. * Formats the given shader snippet from a given type into another one. E.g.
  31179. * this method might be used to convert a simple float string `"1.0"` into a
  31180. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  31181. *
  31182. * @param {String} snippet - The shader snippet.
  31183. * @param {String} fromType - The source type.
  31184. * @param {String} toType - The target type.
  31185. * @return {String} The updated shader string.
  31186. */
  31187. format( snippet, fromType, toType ) {
  31188. fromType = this.getVectorType( fromType );
  31189. toType = this.getVectorType( toType );
  31190. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  31191. return snippet;
  31192. }
  31193. const fromTypeLength = this.getTypeLength( fromType );
  31194. const toTypeLength = this.getTypeLength( toType );
  31195. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  31196. return `${ this.getType( toType ) }(${ snippet }[0].xyz, ${ snippet }[1].xyz, ${ snippet }[2].xyz)`;
  31197. }
  31198. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  31199. return `${ this.getType( toType ) }(${ snippet }[0].xy, ${ snippet }[1].xy)`;
  31200. }
  31201. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  31202. // @TODO: ignore for now
  31203. return snippet;
  31204. }
  31205. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  31206. // @TODO: ignore for now
  31207. return snippet;
  31208. }
  31209. if ( fromTypeLength === toTypeLength ) {
  31210. return `${ this.getType( toType ) }( ${ snippet } )`;
  31211. }
  31212. if ( fromTypeLength > toTypeLength ) {
  31213. return this.format( `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  31214. }
  31215. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  31216. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  31217. }
  31218. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  31219. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  31220. }
  31221. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  31222. // convert a number value to vector type, e.g:
  31223. // vec3( 1u ) -> vec3( float( 1u ) )
  31224. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  31225. }
  31226. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  31227. }
  31228. /**
  31229. * Returns a signature with the engine's current revision.
  31230. *
  31231. * @return {String} The signature.
  31232. */
  31233. getSignature() {
  31234. return `// Three.js r${ REVISION } - Node System\n`;
  31235. }
  31236. // deprecated
  31237. /**
  31238. * @function
  31239. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  31240. *
  31241. * @param {String} [type='NodeMaterial'] - The node material type.
  31242. * @throws {Error}
  31243. */
  31244. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  31245. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  31246. }
  31247. }
  31248. /**
  31249. * Management class for updating nodes. The module tracks metrics like
  31250. * the elapsed time, delta time, the render and frame ID to correctly
  31251. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  31252. * and {@link Node#updateAfter} depending on the node's configuration.
  31253. */
  31254. class NodeFrame {
  31255. /**
  31256. * Constructs a new node fame.
  31257. */
  31258. constructor() {
  31259. /**
  31260. * The elapsed time in seconds.
  31261. *
  31262. * @type {Number}
  31263. * @default 0
  31264. */
  31265. this.time = 0;
  31266. /**
  31267. * The delta time in seconds.
  31268. *
  31269. * @type {Number}
  31270. * @default 0
  31271. */
  31272. this.deltaTime = 0;
  31273. /**
  31274. * The frame ID.
  31275. *
  31276. * @type {Number}
  31277. * @default 0
  31278. */
  31279. this.frameId = 0;
  31280. /**
  31281. * The render ID.
  31282. *
  31283. * @type {Number}
  31284. * @default 0
  31285. */
  31286. this.renderId = 0;
  31287. /**
  31288. * Used to control the {@link Node#update} call.
  31289. *
  31290. * @type {WeakMap<Node, Object>}
  31291. */
  31292. this.updateMap = new WeakMap();
  31293. /**
  31294. * Used to control the {@link Node#updateBefore} call.
  31295. *
  31296. * @type {WeakMap<Node, Object>}
  31297. */
  31298. this.updateBeforeMap = new WeakMap();
  31299. /**
  31300. * Used to control the {@link Node#updateAfter} call.
  31301. *
  31302. * @type {WeakMap<Node, Object>}
  31303. */
  31304. this.updateAfterMap = new WeakMap();
  31305. /**
  31306. * A reference to the current renderer.
  31307. *
  31308. * @type {Renderer?}
  31309. * @default null
  31310. */
  31311. this.renderer = null;
  31312. /**
  31313. * A reference to the current material.
  31314. *
  31315. * @type {Material?}
  31316. * @default null
  31317. */
  31318. this.material = null;
  31319. /**
  31320. * A reference to the current camera.
  31321. *
  31322. * @type {Camera?}
  31323. * @default null
  31324. */
  31325. this.camera = null;
  31326. /**
  31327. * A reference to the current 3D object.
  31328. *
  31329. * @type {Object3D?}
  31330. * @default null
  31331. */
  31332. this.object = null;
  31333. /**
  31334. * A reference to the current scene.
  31335. *
  31336. * @type {Scene?}
  31337. * @default null
  31338. */
  31339. this.scene = null;
  31340. }
  31341. /**
  31342. * Returns a dictionary for a given node and update map which
  31343. * is used to correctly call node update methods per frame or render.
  31344. *
  31345. * @private
  31346. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  31347. * @param {Node} nodeRef - The reference to the current node.
  31348. * @return {Object<String,WeakMap>} The dictionary.
  31349. */
  31350. _getMaps( referenceMap, nodeRef ) {
  31351. let maps = referenceMap.get( nodeRef );
  31352. if ( maps === undefined ) {
  31353. maps = {
  31354. renderMap: new WeakMap(),
  31355. frameMap: new WeakMap()
  31356. };
  31357. referenceMap.set( nodeRef, maps );
  31358. }
  31359. return maps;
  31360. }
  31361. /**
  31362. * This method executes the {@link Node#updateBefore} for the given node.
  31363. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  31364. * is only executed once per frame, render or object depending on the update
  31365. * type.
  31366. *
  31367. * @param {Node} node - The node that should be updated.
  31368. */
  31369. updateBeforeNode( node ) {
  31370. const updateType = node.getUpdateBeforeType();
  31371. const reference = node.updateReference( this );
  31372. if ( updateType === NodeUpdateType.FRAME ) {
  31373. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  31374. if ( frameMap.get( reference ) !== this.frameId ) {
  31375. if ( node.updateBefore( this ) !== false ) {
  31376. frameMap.set( reference, this.frameId );
  31377. }
  31378. }
  31379. } else if ( updateType === NodeUpdateType.RENDER ) {
  31380. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  31381. if ( renderMap.get( reference ) !== this.renderId ) {
  31382. if ( node.updateBefore( this ) !== false ) {
  31383. renderMap.set( reference, this.renderId );
  31384. }
  31385. }
  31386. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31387. node.updateBefore( this );
  31388. }
  31389. }
  31390. /**
  31391. * This method executes the {@link Node#updateAfter} for the given node.
  31392. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  31393. * is only executed once per frame, render or object depending on the update
  31394. * type.
  31395. *
  31396. * @param {Node} node - The node that should be updated.
  31397. */
  31398. updateAfterNode( node ) {
  31399. const updateType = node.getUpdateAfterType();
  31400. const reference = node.updateReference( this );
  31401. if ( updateType === NodeUpdateType.FRAME ) {
  31402. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  31403. if ( frameMap.get( reference ) !== this.frameId ) {
  31404. if ( node.updateAfter( this ) !== false ) {
  31405. frameMap.set( reference, this.frameId );
  31406. }
  31407. }
  31408. } else if ( updateType === NodeUpdateType.RENDER ) {
  31409. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  31410. if ( renderMap.get( reference ) !== this.renderId ) {
  31411. if ( node.updateAfter( this ) !== false ) {
  31412. renderMap.set( reference, this.renderId );
  31413. }
  31414. }
  31415. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31416. node.updateAfter( this );
  31417. }
  31418. }
  31419. /**
  31420. * This method executes the {@link Node#update} for the given node.
  31421. * It makes sure {@link Node#updateType} is honored meaning the update
  31422. * is only executed once per frame, render or object depending on the update
  31423. * type.
  31424. *
  31425. * @param {Node} node - The node that should be updated.
  31426. */
  31427. updateNode( node ) {
  31428. const updateType = node.getUpdateType();
  31429. const reference = node.updateReference( this );
  31430. if ( updateType === NodeUpdateType.FRAME ) {
  31431. const { frameMap } = this._getMaps( this.updateMap, reference );
  31432. if ( frameMap.get( reference ) !== this.frameId ) {
  31433. if ( node.update( this ) !== false ) {
  31434. frameMap.set( reference, this.frameId );
  31435. }
  31436. }
  31437. } else if ( updateType === NodeUpdateType.RENDER ) {
  31438. const { renderMap } = this._getMaps( this.updateMap, reference );
  31439. if ( renderMap.get( reference ) !== this.renderId ) {
  31440. if ( node.update( this ) !== false ) {
  31441. renderMap.set( reference, this.renderId );
  31442. }
  31443. }
  31444. } else if ( updateType === NodeUpdateType.OBJECT ) {
  31445. node.update( this );
  31446. }
  31447. }
  31448. /**
  31449. * Updates the internal state of the node frame. This method is
  31450. * called by the renderer in its internal animation loop.
  31451. */
  31452. update() {
  31453. this.frameId ++;
  31454. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  31455. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  31456. this.lastTime = performance.now();
  31457. this.time += this.deltaTime;
  31458. }
  31459. }
  31460. /**
  31461. * Describes the input of a {@link NodeFunction}.
  31462. */
  31463. class NodeFunctionInput {
  31464. /**
  31465. * Constructs a new node function input.
  31466. *
  31467. * @param {String} type - The input type.
  31468. * @param {String} name - The input name.
  31469. * @param {Number?} [count=null] - If the input is an Array, count will be the length.
  31470. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  31471. * @param {Boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  31472. */
  31473. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  31474. /**
  31475. * The input type.
  31476. *
  31477. * @type {String}
  31478. */
  31479. this.type = type;
  31480. /**
  31481. * The input name.
  31482. *
  31483. * @type {String}
  31484. */
  31485. this.name = name;
  31486. /**
  31487. * If the input is an Array, count will be the length.
  31488. *
  31489. * @type {Number?}
  31490. * @default null
  31491. */
  31492. this.count = count;
  31493. /**
  31494. *The parameter qualifier (only relevant for GLSL).
  31495. *
  31496. * @type {('in'|'out'|'inout')}
  31497. * @default ''
  31498. */
  31499. this.qualifier = qualifier;
  31500. /**
  31501. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  31502. *
  31503. * @type {Boolean}
  31504. * @default false
  31505. */
  31506. this.isConst = isConst;
  31507. }
  31508. }
  31509. NodeFunctionInput.isNodeFunctionInput = true;
  31510. /**
  31511. * Module for representing directional lights as nodes.
  31512. *
  31513. * @augments AnalyticLightNode
  31514. */
  31515. class DirectionalLightNode extends AnalyticLightNode {
  31516. static get type() {
  31517. return 'DirectionalLightNode';
  31518. }
  31519. /**
  31520. * Constructs a new directional light node.
  31521. *
  31522. * @param {DirectionalLight?} [light=null] - The directional light source.
  31523. */
  31524. constructor( light = null ) {
  31525. super( light );
  31526. }
  31527. setup( builder ) {
  31528. super.setup( builder );
  31529. const lightingModel = builder.context.lightingModel;
  31530. const lightColor = this.colorNode;
  31531. const lightDirection = lightTargetDirection( this.light );
  31532. const reflectedLight = builder.context.reflectedLight;
  31533. lightingModel.direct( {
  31534. lightDirection,
  31535. lightColor,
  31536. reflectedLight
  31537. }, builder.stack, builder );
  31538. }
  31539. }
  31540. const _matrix41 = /*@__PURE__*/ new Matrix4();
  31541. const _matrix42 = /*@__PURE__*/ new Matrix4();
  31542. let _ltcLib = null;
  31543. /**
  31544. * Module for representing rect area lights as nodes.
  31545. *
  31546. * @augments AnalyticLightNode
  31547. */
  31548. class RectAreaLightNode extends AnalyticLightNode {
  31549. static get type() {
  31550. return 'RectAreaLightNode';
  31551. }
  31552. /**
  31553. * Constructs a new rect area light node.
  31554. *
  31555. * @param {RectAreaLight?} [light=null] - The rect area light source.
  31556. */
  31557. constructor( light = null ) {
  31558. super( light );
  31559. /**
  31560. * Uniform node representing the half height of the are light.
  31561. *
  31562. * @type {UniformNode<vec3>}
  31563. */
  31564. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  31565. /**
  31566. * Uniform node representing the half width of the are light.
  31567. *
  31568. * @type {UniformNode<vec3>}
  31569. */
  31570. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  31571. /**
  31572. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  31573. * relies on `viewMatrix` which might vary per render call.
  31574. *
  31575. * @type {String}
  31576. * @default 'render'
  31577. */
  31578. this.updateType = NodeUpdateType.RENDER;
  31579. }
  31580. /**
  31581. * Overwritten to updated rect area light specific uniforms.
  31582. *
  31583. * @param {NodeFrame} frame - A reference to the current node frame.
  31584. */
  31585. update( frame ) {
  31586. super.update( frame );
  31587. const { light } = this;
  31588. const viewMatrix = frame.camera.matrixWorldInverse;
  31589. _matrix42.identity();
  31590. _matrix41.copy( light.matrixWorld );
  31591. _matrix41.premultiply( viewMatrix );
  31592. _matrix42.extractRotation( _matrix41 );
  31593. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  31594. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  31595. this.halfWidth.value.applyMatrix4( _matrix42 );
  31596. this.halfHeight.value.applyMatrix4( _matrix42 );
  31597. }
  31598. setup( builder ) {
  31599. super.setup( builder );
  31600. let ltc_1, ltc_2;
  31601. if ( builder.isAvailable( 'float32Filterable' ) ) {
  31602. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  31603. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  31604. } else {
  31605. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  31606. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  31607. }
  31608. const { colorNode, light } = this;
  31609. const lightingModel = builder.context.lightingModel;
  31610. const lightPosition = lightViewPosition( light );
  31611. const reflectedLight = builder.context.reflectedLight;
  31612. lightingModel.directRectArea( {
  31613. lightColor: colorNode,
  31614. lightPosition,
  31615. halfWidth: this.halfWidth,
  31616. halfHeight: this.halfHeight,
  31617. reflectedLight,
  31618. ltc_1,
  31619. ltc_2
  31620. }, builder.stack, builder );
  31621. }
  31622. /**
  31623. * Used to configure the internal BRDF approximation texture data.
  31624. *
  31625. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  31626. */
  31627. static setLTC( ltc ) {
  31628. _ltcLib = ltc;
  31629. }
  31630. }
  31631. /**
  31632. * Module for representing spot lights as nodes.
  31633. *
  31634. * @augments AnalyticLightNode
  31635. */
  31636. class SpotLightNode extends AnalyticLightNode {
  31637. static get type() {
  31638. return 'SpotLightNode';
  31639. }
  31640. /**
  31641. * Constructs a new spot light node.
  31642. *
  31643. * @param {SpotLight?} [light=null] - The spot light source.
  31644. */
  31645. constructor( light = null ) {
  31646. super( light );
  31647. /**
  31648. * Uniform node representing the cone cosine.
  31649. *
  31650. * @type {UniformNode<float>}
  31651. */
  31652. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  31653. /**
  31654. * Uniform node representing the penumbra cosine.
  31655. *
  31656. * @type {UniformNode<float>}
  31657. */
  31658. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  31659. /**
  31660. * Uniform node representing the cutoff distance.
  31661. *
  31662. * @type {UniformNode<float>}
  31663. */
  31664. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  31665. /**
  31666. * Uniform node representing the decay exponent.
  31667. *
  31668. * @type {UniformNode<float>}
  31669. */
  31670. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  31671. }
  31672. /**
  31673. * Overwritten to updated spot light specific uniforms.
  31674. *
  31675. * @param {NodeFrame} frame - A reference to the current node frame.
  31676. */
  31677. update( frame ) {
  31678. super.update( frame );
  31679. const { light } = this;
  31680. this.coneCosNode.value = Math.cos( light.angle );
  31681. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  31682. this.cutoffDistanceNode.value = light.distance;
  31683. this.decayExponentNode.value = light.decay;
  31684. }
  31685. /**
  31686. * Computes the spot attenuation for the given angle.
  31687. *
  31688. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31689. * @return {Node<float>} The spot attenuation.
  31690. */
  31691. getSpotAttenuation( angleCosine ) {
  31692. const { coneCosNode, penumbraCosNode } = this;
  31693. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  31694. }
  31695. setup( builder ) {
  31696. super.setup( builder );
  31697. const lightingModel = builder.context.lightingModel;
  31698. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  31699. const lVector = lightViewPosition( light ).sub( positionView ); // @TODO: Add it into LightNode
  31700. const lightDirection = lVector.normalize();
  31701. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  31702. const spotAttenuation = this.getSpotAttenuation( angleCos );
  31703. const lightDistance = lVector.length();
  31704. const lightAttenuation = getDistanceAttenuation( {
  31705. lightDistance,
  31706. cutoffDistance: cutoffDistanceNode,
  31707. decayExponent: decayExponentNode
  31708. } );
  31709. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  31710. if ( light.map ) {
  31711. const spotLightCoord = lightProjectionUV( light );
  31712. const projectedTexture = texture( light.map, spotLightCoord.xy ).onRenderUpdate( () => light.map );
  31713. const inSpotLightMap = spotLightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  31714. lightColor = inSpotLightMap.select( lightColor.mul( projectedTexture ), lightColor );
  31715. }
  31716. const reflectedLight = builder.context.reflectedLight;
  31717. lightingModel.direct( {
  31718. lightDirection,
  31719. lightColor,
  31720. reflectedLight
  31721. }, builder.stack, builder );
  31722. }
  31723. }
  31724. /**
  31725. * An IES version of the default spot light node.
  31726. *
  31727. * @augments SpotLightNode
  31728. */
  31729. class IESSpotLightNode extends SpotLightNode {
  31730. static get type() {
  31731. return 'IESSpotLightNode';
  31732. }
  31733. /**
  31734. * Overwrites the default implementation to compute an IES conform spot attenuation.
  31735. *
  31736. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  31737. * @return {Node<float>} The spot attenuation.
  31738. */
  31739. getSpotAttenuation( angleCosine ) {
  31740. const iesMap = this.light.iesMap;
  31741. let spotAttenuation = null;
  31742. if ( iesMap && iesMap.isTexture === true ) {
  31743. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  31744. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  31745. } else {
  31746. spotAttenuation = super.getSpotAttenuation( angleCosine );
  31747. }
  31748. return spotAttenuation;
  31749. }
  31750. }
  31751. /**
  31752. * Module for representing ambient lights as nodes.
  31753. *
  31754. * @augments AnalyticLightNode
  31755. */
  31756. class AmbientLightNode extends AnalyticLightNode {
  31757. static get type() {
  31758. return 'AmbientLightNode';
  31759. }
  31760. /**
  31761. * Constructs a new ambient light node.
  31762. *
  31763. * @param {AmbientLight?} [light=null] - The ambient light source.
  31764. */
  31765. constructor( light = null ) {
  31766. super( light );
  31767. }
  31768. setup( { context } ) {
  31769. context.irradiance.addAssign( this.colorNode );
  31770. }
  31771. }
  31772. /**
  31773. * Module for representing hemisphere lights as nodes.
  31774. *
  31775. * @augments AnalyticLightNode
  31776. */
  31777. class HemisphereLightNode extends AnalyticLightNode {
  31778. static get type() {
  31779. return 'HemisphereLightNode';
  31780. }
  31781. /**
  31782. * Constructs a new hemisphere light node.
  31783. *
  31784. * @param {HemisphereLight?} [light=null] - The hemisphere light source.
  31785. */
  31786. constructor( light = null ) {
  31787. super( light );
  31788. /**
  31789. * Uniform node representing the light's position.
  31790. *
  31791. * @type {UniformNode<vec3>}
  31792. */
  31793. this.lightPositionNode = lightPosition( light );
  31794. /**
  31795. * A node representing the light's direction.
  31796. *
  31797. * @type {Node<vec3>}
  31798. */
  31799. this.lightDirectionNode = this.lightPositionNode.normalize();
  31800. /**
  31801. * Uniform node representing the light's ground color.
  31802. *
  31803. * @type {UniformNode<vec3>}
  31804. */
  31805. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  31806. }
  31807. /**
  31808. * Overwritten to updated hemisphere light specific uniforms.
  31809. *
  31810. * @param {NodeFrame} frame - A reference to the current node frame.
  31811. */
  31812. update( frame ) {
  31813. const { light } = this;
  31814. super.update( frame );
  31815. this.lightPositionNode.object3d = light;
  31816. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  31817. }
  31818. setup( builder ) {
  31819. const { colorNode, groundColorNode, lightDirectionNode } = this;
  31820. const dotNL = normalView.dot( lightDirectionNode );
  31821. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  31822. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  31823. builder.context.irradiance.addAssign( irradiance );
  31824. }
  31825. }
  31826. /**
  31827. * Module for representing light probes as nodes.
  31828. *
  31829. * @augments AnalyticLightNode
  31830. */
  31831. class LightProbeNode extends AnalyticLightNode {
  31832. static get type() {
  31833. return 'LightProbeNode';
  31834. }
  31835. /**
  31836. * Constructs a new light probe node.
  31837. *
  31838. * @param {LightProbe?} [light=null] - The light probe.
  31839. */
  31840. constructor( light = null ) {
  31841. super( light );
  31842. const array = [];
  31843. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  31844. /**
  31845. * Light probe represented as a uniform of spherical harmonics.
  31846. *
  31847. * @type {UniformArrayNode}
  31848. */
  31849. this.lightProbe = uniformArray( array );
  31850. }
  31851. /**
  31852. * Overwritten to updated light probe specific uniforms.
  31853. *
  31854. * @param {NodeFrame} frame - A reference to the current node frame.
  31855. */
  31856. update( frame ) {
  31857. const { light } = this;
  31858. super.update( frame );
  31859. //
  31860. for ( let i = 0; i < 9; i ++ ) {
  31861. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  31862. }
  31863. }
  31864. setup( builder ) {
  31865. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  31866. builder.context.irradiance.addAssign( irradiance );
  31867. }
  31868. }
  31869. /**
  31870. * Base class for node parsers. A derived parser must be implemented
  31871. * for each supported native shader language.
  31872. */
  31873. class NodeParser {
  31874. /**
  31875. * The method parses the given native code an returns a node function.
  31876. *
  31877. * @abstract
  31878. * @param {String} source - The native shader code.
  31879. * @return {NodeFunction} A node function.
  31880. */
  31881. parseFunction( /*source*/ ) {
  31882. console.warn( 'Abstract function.' );
  31883. }
  31884. }
  31885. /**
  31886. * Base class for node functions. A derived module must be implemented
  31887. * for each supported native shader language. Similar to other `Node*` modules,
  31888. * this class is only relevant during the building process and not used
  31889. * in user-level code.
  31890. */
  31891. class NodeFunction {
  31892. /**
  31893. * Constructs a new node function.
  31894. *
  31895. * @param {String} type - The node type. This type is the return type of the node function.
  31896. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  31897. * @param {String} [name=''] - The function's name.
  31898. * @param {String} [precision=''] - The precision qualifier.
  31899. */
  31900. constructor( type, inputs, name = '', precision = '' ) {
  31901. /**
  31902. * The node type. This type is the return type of the node function.
  31903. *
  31904. * @type {String}
  31905. */
  31906. this.type = type;
  31907. /**
  31908. * The function's inputs.
  31909. *
  31910. * @type {Array<NodeFunctionInput>}
  31911. */
  31912. this.inputs = inputs;
  31913. /**
  31914. * The name of the uniform.
  31915. *
  31916. * @type {String}
  31917. * @default ''
  31918. */
  31919. this.name = name;
  31920. /**
  31921. * The precision qualifier.
  31922. *
  31923. * @type {String}
  31924. * @default ''
  31925. */
  31926. this.precision = precision;
  31927. }
  31928. /**
  31929. * This method returns the native code of the node function.
  31930. *
  31931. * @abstract
  31932. * @param {String} name - The function's name.
  31933. * @return {String} A shader code.
  31934. */
  31935. getCode( /*name = this.name*/ ) {
  31936. console.warn( 'Abstract function.' );
  31937. }
  31938. }
  31939. NodeFunction.isNodeFunction = true;
  31940. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  31941. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  31942. const pragmaMain = '#pragma main';
  31943. const parse$1 = ( source ) => {
  31944. source = source.trim();
  31945. const pragmaMainIndex = source.indexOf( pragmaMain );
  31946. const mainCode = pragmaMainIndex !== - 1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  31947. const declaration = mainCode.match( declarationRegexp$1 );
  31948. if ( declaration !== null && declaration.length === 5 ) {
  31949. // tokenizer
  31950. const inputsCode = declaration[ 4 ];
  31951. const propsMatches = [];
  31952. let nameMatch = null;
  31953. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  31954. propsMatches.push( nameMatch );
  31955. }
  31956. // parser
  31957. const inputs = [];
  31958. let i = 0;
  31959. while ( i < propsMatches.length ) {
  31960. const isConst = propsMatches[ i ][ 0 ] === 'const';
  31961. if ( isConst === true ) {
  31962. i ++;
  31963. }
  31964. let qualifier = propsMatches[ i ][ 0 ];
  31965. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  31966. i ++;
  31967. } else {
  31968. qualifier = '';
  31969. }
  31970. const type = propsMatches[ i ++ ][ 0 ];
  31971. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  31972. if ( Number.isNaN( count ) === false ) i ++;
  31973. else count = null;
  31974. const name = propsMatches[ i ++ ][ 0 ];
  31975. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  31976. }
  31977. //
  31978. const blockCode = mainCode.substring( declaration[ 0 ].length );
  31979. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  31980. const type = declaration[ 2 ];
  31981. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  31982. const headerCode = pragmaMainIndex !== - 1 ? source.slice( 0, pragmaMainIndex ) : '';
  31983. return {
  31984. type,
  31985. inputs,
  31986. name,
  31987. precision,
  31988. inputsCode,
  31989. blockCode,
  31990. headerCode
  31991. };
  31992. } else {
  31993. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  31994. }
  31995. };
  31996. /**
  31997. * This class represents a GLSL node function.
  31998. *
  31999. * @augments NodeFunction
  32000. */
  32001. class GLSLNodeFunction extends NodeFunction {
  32002. /**
  32003. * Constructs a new GLSL node function.
  32004. *
  32005. * @param {String} source - The GLSL source.
  32006. */
  32007. constructor( source ) {
  32008. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  32009. super( type, inputs, name, precision );
  32010. this.inputsCode = inputsCode;
  32011. this.blockCode = blockCode;
  32012. this.headerCode = headerCode;
  32013. }
  32014. /**
  32015. * This method returns the GLSL code of the node function.
  32016. *
  32017. * @param {String} [name=this.name] - The function's name.
  32018. * @return {String} The shader code.
  32019. */
  32020. getCode( name = this.name ) {
  32021. let code;
  32022. const blockCode = this.blockCode;
  32023. if ( blockCode !== '' ) {
  32024. const { type, inputsCode, headerCode, precision } = this;
  32025. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  32026. if ( precision !== '' ) {
  32027. declarationCode = `${ precision } ${ declarationCode }`;
  32028. }
  32029. code = headerCode + declarationCode + blockCode;
  32030. } else {
  32031. // interface function
  32032. code = '';
  32033. }
  32034. return code;
  32035. }
  32036. }
  32037. /**
  32038. * A GLSL node parser.
  32039. *
  32040. * @augments NodeParser
  32041. */
  32042. class GLSLNodeParser extends NodeParser {
  32043. /**
  32044. * The method parses the given GLSL code an returns a node function.
  32045. *
  32046. * @param {String} source - The GLSL code.
  32047. * @return {GLSLNodeFunction} A node function.
  32048. */
  32049. parseFunction( source ) {
  32050. return new GLSLNodeFunction( source );
  32051. }
  32052. }
  32053. const _outputNodeMap = new WeakMap();
  32054. const _chainKeys$2 = [];
  32055. const _cacheKeyValues = [];
  32056. /**
  32057. * This renderer module manages node-related objects and is the
  32058. * primary interface between the renderer and the node system.
  32059. *
  32060. * @private
  32061. * @augments DataMap
  32062. */
  32063. class Nodes extends DataMap {
  32064. /**
  32065. * Constructs a new nodes management component.
  32066. *
  32067. * @param {Renderer} renderer - The renderer.
  32068. * @param {Backend} backend - The renderer's backend.
  32069. */
  32070. constructor( renderer, backend ) {
  32071. super();
  32072. /**
  32073. * The renderer.
  32074. *
  32075. * @type {Renderer}
  32076. */
  32077. this.renderer = renderer;
  32078. /**
  32079. * The renderer's backend.
  32080. *
  32081. * @type {Backend}
  32082. */
  32083. this.backend = backend;
  32084. /**
  32085. * The node frame.
  32086. *
  32087. * @type {Renderer}
  32088. */
  32089. this.nodeFrame = new NodeFrame();
  32090. /**
  32091. * A cache for managing node builder states.
  32092. *
  32093. * @type {Map<Number,NodeBuilderState>}
  32094. */
  32095. this.nodeBuilderCache = new Map();
  32096. /**
  32097. * A cache for managing data cache key data.
  32098. *
  32099. * @type {ChainMap}
  32100. */
  32101. this.callHashCache = new ChainMap();
  32102. /**
  32103. * A cache for managing node uniforms group data.
  32104. *
  32105. * @type {ChainMap}
  32106. */
  32107. this.groupsData = new ChainMap();
  32108. /**
  32109. * A cache for managing node objects of
  32110. * scene properties like fog or environments.
  32111. *
  32112. * @type {Object<String,WeakMap>}
  32113. */
  32114. this.cacheLib = {};
  32115. }
  32116. /**
  32117. * Returns `true` if the given node uniforms group must be updated or not.
  32118. *
  32119. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  32120. * @return {Boolean} Whether the node uniforms group requires an update or not.
  32121. */
  32122. updateGroup( nodeUniformsGroup ) {
  32123. const groupNode = nodeUniformsGroup.groupNode;
  32124. const name = groupNode.name;
  32125. // objectGroup is always updated
  32126. if ( name === objectGroup.name ) return true;
  32127. // renderGroup is updated once per render/compute call
  32128. if ( name === renderGroup.name ) {
  32129. const uniformsGroupData = this.get( nodeUniformsGroup );
  32130. const renderId = this.nodeFrame.renderId;
  32131. if ( uniformsGroupData.renderId !== renderId ) {
  32132. uniformsGroupData.renderId = renderId;
  32133. return true;
  32134. }
  32135. return false;
  32136. }
  32137. // frameGroup is updated once per frame
  32138. if ( name === frameGroup.name ) {
  32139. const uniformsGroupData = this.get( nodeUniformsGroup );
  32140. const frameId = this.nodeFrame.frameId;
  32141. if ( uniformsGroupData.frameId !== frameId ) {
  32142. uniformsGroupData.frameId = frameId;
  32143. return true;
  32144. }
  32145. return false;
  32146. }
  32147. // other groups are updated just when groupNode.needsUpdate is true
  32148. _chainKeys$2[ 0 ] = groupNode;
  32149. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  32150. let groupData = this.groupsData.get( _chainKeys$2 );
  32151. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  32152. _chainKeys$2.length = 0;
  32153. if ( groupData.version !== groupNode.version ) {
  32154. groupData.version = groupNode.version;
  32155. return true;
  32156. }
  32157. return false;
  32158. }
  32159. /**
  32160. * Returns the cache key for the given render object.
  32161. *
  32162. * @param {RenderObject} renderObject - The render object.
  32163. * @return {Number} The cache key.
  32164. */
  32165. getForRenderCacheKey( renderObject ) {
  32166. return renderObject.initialCacheKey;
  32167. }
  32168. /**
  32169. * Returns a node builder state for the given render object.
  32170. *
  32171. * @param {RenderObject} renderObject - The render object.
  32172. * @return {NodeBuilderState} The node builder state.
  32173. */
  32174. getForRender( renderObject ) {
  32175. const renderObjectData = this.get( renderObject );
  32176. let nodeBuilderState = renderObjectData.nodeBuilderState;
  32177. if ( nodeBuilderState === undefined ) {
  32178. const { nodeBuilderCache } = this;
  32179. const cacheKey = this.getForRenderCacheKey( renderObject );
  32180. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  32181. if ( nodeBuilderState === undefined ) {
  32182. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  32183. nodeBuilder.scene = renderObject.scene;
  32184. nodeBuilder.material = renderObject.material;
  32185. nodeBuilder.camera = renderObject.camera;
  32186. nodeBuilder.context.material = renderObject.material;
  32187. nodeBuilder.lightsNode = renderObject.lightsNode;
  32188. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  32189. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  32190. nodeBuilder.clippingContext = renderObject.clippingContext;
  32191. nodeBuilder.build();
  32192. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32193. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  32194. }
  32195. nodeBuilderState.usedTimes ++;
  32196. renderObjectData.nodeBuilderState = nodeBuilderState;
  32197. }
  32198. return nodeBuilderState;
  32199. }
  32200. /**
  32201. * Deletes the given object from the internal data map
  32202. *
  32203. * @param {Any} object - The object to delete.
  32204. * @return {Object?} The deleted dictionary.
  32205. */
  32206. delete( object ) {
  32207. if ( object.isRenderObject ) {
  32208. const nodeBuilderState = this.get( object ).nodeBuilderState;
  32209. nodeBuilderState.usedTimes --;
  32210. if ( nodeBuilderState.usedTimes === 0 ) {
  32211. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  32212. }
  32213. }
  32214. return super.delete( object );
  32215. }
  32216. /**
  32217. * Returns a node builder state for the given compute node.
  32218. *
  32219. * @param {Node} computeNode - The compute node.
  32220. * @return {NodeBuilderState} The node builder state.
  32221. */
  32222. getForCompute( computeNode ) {
  32223. const computeData = this.get( computeNode );
  32224. let nodeBuilderState = computeData.nodeBuilderState;
  32225. if ( nodeBuilderState === undefined ) {
  32226. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  32227. nodeBuilder.build();
  32228. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  32229. computeData.nodeBuilderState = nodeBuilderState;
  32230. }
  32231. return nodeBuilderState;
  32232. }
  32233. /**
  32234. * Creates a node builder state for the given node builder.
  32235. *
  32236. * @private
  32237. * @param {NodeBuilder} nodeBuilder - The node builder.
  32238. * @return {NodeBuilderState} The node builder state.
  32239. */
  32240. _createNodeBuilderState( nodeBuilder ) {
  32241. return new NodeBuilderState(
  32242. nodeBuilder.vertexShader,
  32243. nodeBuilder.fragmentShader,
  32244. nodeBuilder.computeShader,
  32245. nodeBuilder.getAttributesArray(),
  32246. nodeBuilder.getBindings(),
  32247. nodeBuilder.updateNodes,
  32248. nodeBuilder.updateBeforeNodes,
  32249. nodeBuilder.updateAfterNodes,
  32250. nodeBuilder.monitor,
  32251. nodeBuilder.transforms
  32252. );
  32253. }
  32254. /**
  32255. * Returns an environment node for the current configured
  32256. * scene environment.
  32257. *
  32258. * @param {Scene} scene - The scene.
  32259. * @return {Node} A node representing the current scene environment.
  32260. */
  32261. getEnvironmentNode( scene ) {
  32262. this.updateEnvironment( scene );
  32263. let environmentNode = null;
  32264. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  32265. environmentNode = scene.environmentNode;
  32266. } else {
  32267. const sceneData = this.get( scene );
  32268. if ( sceneData.environmentNode ) {
  32269. environmentNode = sceneData.environmentNode;
  32270. }
  32271. }
  32272. return environmentNode;
  32273. }
  32274. /**
  32275. * Returns a background node for the current configured
  32276. * scene background.
  32277. *
  32278. * @param {Scene} scene - The scene.
  32279. * @return {Node} A node representing the current scene background.
  32280. */
  32281. getBackgroundNode( scene ) {
  32282. this.updateBackground( scene );
  32283. let backgroundNode = null;
  32284. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  32285. backgroundNode = scene.backgroundNode;
  32286. } else {
  32287. const sceneData = this.get( scene );
  32288. if ( sceneData.backgroundNode ) {
  32289. backgroundNode = sceneData.backgroundNode;
  32290. }
  32291. }
  32292. return backgroundNode;
  32293. }
  32294. /**
  32295. * Returns a fog node for the current configured scene fog.
  32296. *
  32297. * @param {Scene} scene - The scene.
  32298. * @return {Node} A node representing the current scene fog.
  32299. */
  32300. getFogNode( scene ) {
  32301. this.updateFog( scene );
  32302. return scene.fogNode || this.get( scene ).fogNode || null;
  32303. }
  32304. /**
  32305. * Returns a cache key for the given scene and lights node.
  32306. * This key is used by `RenderObject` as a part of the dynamic
  32307. * cache key (a key that must be checked every time the render
  32308. * objects is drawn).
  32309. *
  32310. * @param {Scene} scene - The scene.
  32311. * @param {LightsNode} lightsNode - The lights node.
  32312. * @return {Number} The cache key.
  32313. */
  32314. getCacheKey( scene, lightsNode ) {
  32315. _chainKeys$2[ 0 ] = scene;
  32316. _chainKeys$2[ 1 ] = lightsNode;
  32317. const callId = this.renderer.info.calls;
  32318. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  32319. if ( cacheKeyData.callId !== callId ) {
  32320. const environmentNode = this.getEnvironmentNode( scene );
  32321. const fogNode = this.getFogNode( scene );
  32322. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  32323. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  32324. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  32325. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  32326. cacheKeyData.callId = callId;
  32327. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  32328. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  32329. _cacheKeyValues.length = 0;
  32330. }
  32331. _chainKeys$2.length = 0;
  32332. return cacheKeyData.cacheKey;
  32333. }
  32334. /**
  32335. * A boolean that indicates whether tone mapping should be enabled
  32336. * or not.
  32337. *
  32338. * @type {Boolean}
  32339. */
  32340. get isToneMappingState() {
  32341. return this.renderer.getRenderTarget() ? false : true;
  32342. }
  32343. /**
  32344. * If a scene background is configured, this method makes sure to
  32345. * represent the background with a corresponding node-based implementation.
  32346. *
  32347. * @param {Scene} scene - The scene.
  32348. */
  32349. updateBackground( scene ) {
  32350. const sceneData = this.get( scene );
  32351. const background = scene.background;
  32352. if ( background ) {
  32353. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  32354. if ( sceneData.background !== background || forceUpdate ) {
  32355. const backgroundNode = this.getCacheNode( 'background', background, () => {
  32356. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  32357. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  32358. return pmremTexture( background );
  32359. } else {
  32360. let envMap;
  32361. if ( background.isCubeTexture === true ) {
  32362. envMap = cubeTexture( background );
  32363. } else {
  32364. envMap = texture( background );
  32365. }
  32366. return cubeMapNode( envMap );
  32367. }
  32368. } else if ( background.isTexture === true ) {
  32369. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  32370. } else if ( background.isColor !== true ) {
  32371. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  32372. }
  32373. }, forceUpdate );
  32374. sceneData.backgroundNode = backgroundNode;
  32375. sceneData.background = background;
  32376. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  32377. }
  32378. } else if ( sceneData.backgroundNode ) {
  32379. delete sceneData.backgroundNode;
  32380. delete sceneData.background;
  32381. }
  32382. }
  32383. /**
  32384. * This method is part of the caching of nodes which are used to represents the
  32385. * scene's background, fog or environment.
  32386. *
  32387. * @param {String} type - The type of object to cache.
  32388. * @param {Object} object - The object.
  32389. * @param {Function} callback - A callback that produces a node representation for the given object.
  32390. * @param {Boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  32391. * @return {Node} The node representation.
  32392. */
  32393. getCacheNode( type, object, callback, forceUpdate = false ) {
  32394. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  32395. let node = nodeCache.get( object );
  32396. if ( node === undefined || forceUpdate ) {
  32397. node = callback();
  32398. nodeCache.set( object, node );
  32399. }
  32400. return node;
  32401. }
  32402. /**
  32403. * If a scene fog is configured, this method makes sure to
  32404. * represent the fog with a corresponding node-based implementation.
  32405. *
  32406. * @param {Scene} scene - The scene.
  32407. */
  32408. updateFog( scene ) {
  32409. const sceneData = this.get( scene );
  32410. const sceneFog = scene.fog;
  32411. if ( sceneFog ) {
  32412. if ( sceneData.fog !== sceneFog ) {
  32413. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  32414. if ( sceneFog.isFogExp2 ) {
  32415. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32416. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  32417. return fog( color, densityFogFactor( density ) );
  32418. } else if ( sceneFog.isFog ) {
  32419. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  32420. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  32421. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  32422. return fog( color, rangeFogFactor( near, far ) );
  32423. } else {
  32424. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  32425. }
  32426. } );
  32427. sceneData.fogNode = fogNode;
  32428. sceneData.fog = sceneFog;
  32429. }
  32430. } else {
  32431. delete sceneData.fogNode;
  32432. delete sceneData.fog;
  32433. }
  32434. }
  32435. /**
  32436. * If a scene environment is configured, this method makes sure to
  32437. * represent the environment with a corresponding node-based implementation.
  32438. *
  32439. * @param {Scene} scene - The scene.
  32440. */
  32441. updateEnvironment( scene ) {
  32442. const sceneData = this.get( scene );
  32443. const environment = scene.environment;
  32444. if ( environment ) {
  32445. if ( sceneData.environment !== environment ) {
  32446. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  32447. if ( environment.isCubeTexture === true ) {
  32448. return cubeTexture( environment );
  32449. } else if ( environment.isTexture === true ) {
  32450. return texture( environment );
  32451. } else {
  32452. console.error( 'Nodes: Unsupported environment configuration.', environment );
  32453. }
  32454. } );
  32455. sceneData.environmentNode = environmentNode;
  32456. sceneData.environment = environment;
  32457. }
  32458. } else if ( sceneData.environmentNode ) {
  32459. delete sceneData.environmentNode;
  32460. delete sceneData.environment;
  32461. }
  32462. }
  32463. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  32464. const nodeFrame = this.nodeFrame;
  32465. nodeFrame.renderer = renderer;
  32466. nodeFrame.scene = scene;
  32467. nodeFrame.object = object;
  32468. nodeFrame.camera = camera;
  32469. nodeFrame.material = material;
  32470. return nodeFrame;
  32471. }
  32472. getNodeFrameForRender( renderObject ) {
  32473. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  32474. }
  32475. /**
  32476. * Returns the current output cache key.
  32477. *
  32478. * @return {String} The output cache key.
  32479. */
  32480. getOutputCacheKey() {
  32481. const renderer = this.renderer;
  32482. return renderer.toneMapping + ',' + renderer.currentColorSpace;
  32483. }
  32484. /**
  32485. * Checks if the output configuration (tone mapping and color space) for
  32486. * the given target has changed.
  32487. *
  32488. * @param {Texture} outputTarget - The output target.
  32489. * @return {Boolean} Whether the output configuration has changed or not.
  32490. */
  32491. hasOutputChange( outputTarget ) {
  32492. const cacheKey = _outputNodeMap.get( outputTarget );
  32493. return cacheKey !== this.getOutputCacheKey();
  32494. }
  32495. /**
  32496. * Returns a node that represents the output configuration (tone mapping and
  32497. * color space) for the current target.
  32498. *
  32499. * @param {Texture} outputTarget - The output target.
  32500. * @return {Node} The output node.
  32501. */
  32502. getOutputNode( outputTarget ) {
  32503. const renderer = this.renderer;
  32504. const cacheKey = this.getOutputCacheKey();
  32505. const output = texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  32506. _outputNodeMap.set( outputTarget, cacheKey );
  32507. return output;
  32508. }
  32509. /**
  32510. * Triggers the call of `updateBefore()` methods
  32511. * for all nodes of the given render object.
  32512. *
  32513. * @param {RenderObject} renderObject - The render object.
  32514. */
  32515. updateBefore( renderObject ) {
  32516. const nodeBuilder = renderObject.getNodeBuilderState();
  32517. for ( const node of nodeBuilder.updateBeforeNodes ) {
  32518. // update frame state for each node
  32519. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  32520. }
  32521. }
  32522. /**
  32523. * Triggers the call of `updateAfter()` methods
  32524. * for all nodes of the given render object.
  32525. *
  32526. * @param {RenderObject} renderObject - The render object.
  32527. */
  32528. updateAfter( renderObject ) {
  32529. const nodeBuilder = renderObject.getNodeBuilderState();
  32530. for ( const node of nodeBuilder.updateAfterNodes ) {
  32531. // update frame state for each node
  32532. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  32533. }
  32534. }
  32535. /**
  32536. * Triggers the call of `update()` methods
  32537. * for all nodes of the given compute node.
  32538. *
  32539. * @param {Node} computeNode - The compute node.
  32540. */
  32541. updateForCompute( computeNode ) {
  32542. const nodeFrame = this.getNodeFrame();
  32543. const nodeBuilder = this.getForCompute( computeNode );
  32544. for ( const node of nodeBuilder.updateNodes ) {
  32545. nodeFrame.updateNode( node );
  32546. }
  32547. }
  32548. /**
  32549. * Triggers the call of `update()` methods
  32550. * for all nodes of the given compute node.
  32551. *
  32552. * @param {RenderObject} renderObject - The render object.
  32553. */
  32554. updateForRender( renderObject ) {
  32555. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32556. const nodeBuilder = renderObject.getNodeBuilderState();
  32557. for ( const node of nodeBuilder.updateNodes ) {
  32558. nodeFrame.updateNode( node );
  32559. }
  32560. }
  32561. /**
  32562. * Returns `true` if the given render object requires a refresh.
  32563. *
  32564. * @param {RenderObject} renderObject - The render object.
  32565. * @return {Boolean} Whether the given render object requires a refresh or not.
  32566. */
  32567. needsRefresh( renderObject ) {
  32568. const nodeFrame = this.getNodeFrameForRender( renderObject );
  32569. const monitor = renderObject.getMonitor();
  32570. return monitor.needsRefresh( renderObject, nodeFrame );
  32571. }
  32572. /**
  32573. * Frees the internal resources.
  32574. */
  32575. dispose() {
  32576. super.dispose();
  32577. this.nodeFrame = new NodeFrame();
  32578. this.nodeBuilderCache = new Map();
  32579. this.cacheLib = {};
  32580. }
  32581. }
  32582. const _plane = /*@__PURE__*/ new Plane();
  32583. /**
  32584. * Represents the state that is used to perform clipping via clipping planes.
  32585. * There is a default clipping context for each render context. When the
  32586. * scene holds instances of `ClippingGroup`, there will be a context for each
  32587. * group.
  32588. *
  32589. * @private
  32590. */
  32591. class ClippingContext {
  32592. /**
  32593. * Constructs a new clipping context.
  32594. *
  32595. * @param {ClippingContext?} [parentContext=null] - A reference to the parent clipping context.
  32596. */
  32597. constructor( parentContext = null ) {
  32598. /**
  32599. * The clipping context's version.
  32600. *
  32601. * @type {Number}
  32602. * @readonly
  32603. */
  32604. this.version = 0;
  32605. /**
  32606. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  32607. *
  32608. * @type {Boolean?}
  32609. * @default null
  32610. */
  32611. this.clipIntersection = null;
  32612. /**
  32613. * The clipping context's cache key.
  32614. *
  32615. * @type {String}
  32616. */
  32617. this.cacheKey = '';
  32618. /**
  32619. * Whether the shadow pass is active or not.
  32620. *
  32621. * @type {Boolean}
  32622. * @default false
  32623. */
  32624. this.shadowPass = false;
  32625. /**
  32626. * The view normal matrix.
  32627. *
  32628. * @type {Matrix3}
  32629. */
  32630. this.viewNormalMatrix = new Matrix3();
  32631. /**
  32632. * Internal cache for maintaining clipping contexts.
  32633. *
  32634. * @type {WeakMap<ClippingGroup,ClippingContext>}
  32635. */
  32636. this.clippingGroupContexts = new WeakMap();
  32637. /**
  32638. * The intersection planes.
  32639. *
  32640. * @type {Array<Vector4>}
  32641. */
  32642. this.intersectionPlanes = [];
  32643. /**
  32644. * The intersection planes.
  32645. *
  32646. * @type {Array<Vector4>}
  32647. */
  32648. this.unionPlanes = [];
  32649. /**
  32650. * The version of the clipping context's parent context.
  32651. *
  32652. * @type {Number?}
  32653. * @readonly
  32654. */
  32655. this.parentVersion = null;
  32656. if ( parentContext !== null ) {
  32657. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  32658. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  32659. this.shadowPass = parentContext.shadowPass;
  32660. this.viewMatrix = parentContext.viewMatrix;
  32661. }
  32662. }
  32663. /**
  32664. * Projects the given source clipping planes and writes the result into the
  32665. * destination array.
  32666. *
  32667. * @param {Array<Plane>} source - The source clipping planes.
  32668. * @param {Array<Vector4>} destination - The destination.
  32669. * @param {Number} offset - The offset.
  32670. */
  32671. projectPlanes( source, destination, offset ) {
  32672. const l = source.length;
  32673. for ( let i = 0; i < l; i ++ ) {
  32674. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  32675. const v = destination[ offset + i ];
  32676. const normal = _plane.normal;
  32677. v.x = - normal.x;
  32678. v.y = - normal.y;
  32679. v.z = - normal.z;
  32680. v.w = _plane.constant;
  32681. }
  32682. }
  32683. /**
  32684. * Updates the root clipping context of a scene.
  32685. *
  32686. * @param {Scene} scene - The scene.
  32687. * @param {Camera} camera - The camera that is used to render the scene.
  32688. */
  32689. updateGlobal( scene, camera ) {
  32690. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  32691. this.viewMatrix = camera.matrixWorldInverse;
  32692. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  32693. }
  32694. /**
  32695. * Updates the clipping context.
  32696. *
  32697. * @param {ClippingContext} parentContext - The parent context.
  32698. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  32699. */
  32700. update( parentContext, clippingGroup ) {
  32701. let update = false;
  32702. if ( parentContext.version !== this.parentVersion ) {
  32703. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  32704. this.unionPlanes = Array.from( parentContext.unionPlanes );
  32705. this.parentVersion = parentContext.version;
  32706. }
  32707. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  32708. this.clipIntersection = clippingGroup.clipIntersection;
  32709. if ( this.clipIntersection ) {
  32710. this.unionPlanes.length = parentContext.unionPlanes.length;
  32711. } else {
  32712. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  32713. }
  32714. }
  32715. const srcClippingPlanes = clippingGroup.clippingPlanes;
  32716. const l = srcClippingPlanes.length;
  32717. let dstClippingPlanes;
  32718. let offset;
  32719. if ( this.clipIntersection ) {
  32720. dstClippingPlanes = this.intersectionPlanes;
  32721. offset = parentContext.intersectionPlanes.length;
  32722. } else {
  32723. dstClippingPlanes = this.unionPlanes;
  32724. offset = parentContext.unionPlanes.length;
  32725. }
  32726. if ( dstClippingPlanes.length !== offset + l ) {
  32727. dstClippingPlanes.length = offset + l;
  32728. for ( let i = 0; i < l; i ++ ) {
  32729. dstClippingPlanes[ offset + i ] = new Vector4();
  32730. }
  32731. update = true;
  32732. }
  32733. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  32734. if ( update ) {
  32735. this.version ++;
  32736. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  32737. }
  32738. }
  32739. /**
  32740. * Returns a clipping context for the given clipping group.
  32741. *
  32742. * @param {ClippingGroup} clippingGroup - The clipping group.
  32743. * @return {ClippingContext} The clipping context.
  32744. */
  32745. getGroupContext( clippingGroup ) {
  32746. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  32747. let context = this.clippingGroupContexts.get( clippingGroup );
  32748. if ( context === undefined ) {
  32749. context = new ClippingContext( this );
  32750. this.clippingGroupContexts.set( clippingGroup, context );
  32751. }
  32752. context.update( this, clippingGroup );
  32753. return context;
  32754. }
  32755. /**
  32756. * The count of union clipping planes.
  32757. *
  32758. * @type {Number}
  32759. * @readonly
  32760. */
  32761. get unionClippingCount() {
  32762. return this.unionPlanes.length;
  32763. }
  32764. }
  32765. /**
  32766. * This module is used to represent render bundles inside the renderer
  32767. * for further processing.
  32768. *
  32769. * @private
  32770. */
  32771. class RenderBundle {
  32772. /**
  32773. * Constructs a new bundle group.
  32774. *
  32775. * @param {BundleGroup} bundleGroup - The bundle group.
  32776. * @param {Camera} camera - The camera the bundle group is rendered with.
  32777. */
  32778. constructor( bundleGroup, camera ) {
  32779. this.bundleGroup = bundleGroup;
  32780. this.camera = camera;
  32781. }
  32782. }
  32783. const _chainKeys$1 = [];
  32784. /**
  32785. * This renderer module manages render bundles.
  32786. *
  32787. * @private
  32788. */
  32789. class RenderBundles {
  32790. /**
  32791. * Constructs a new render bundle management component.
  32792. */
  32793. constructor() {
  32794. /**
  32795. * A chain map for maintaining the render bundles.
  32796. *
  32797. * @type {ChainMap}
  32798. */
  32799. this.bundles = new ChainMap();
  32800. }
  32801. /**
  32802. * Returns a render bundle for the given bundle group and camera.
  32803. *
  32804. * @param {BundleGroup} bundleGroup - The bundle group.
  32805. * @param {Camera} camera - The camera the bundle group is rendered with.
  32806. * @return {RenderBundle} The render bundle.
  32807. */
  32808. get( bundleGroup, camera ) {
  32809. const bundles = this.bundles;
  32810. _chainKeys$1[ 0 ] = bundleGroup;
  32811. _chainKeys$1[ 1 ] = camera;
  32812. let bundle = bundles.get( _chainKeys$1 );
  32813. if ( bundle === undefined ) {
  32814. bundle = new RenderBundle( bundleGroup, camera );
  32815. bundles.set( _chainKeys$1, bundle );
  32816. }
  32817. _chainKeys$1.length = 0;
  32818. return bundle;
  32819. }
  32820. /**
  32821. * Frees all internal resources.
  32822. */
  32823. dispose() {
  32824. this.bundles = new ChainMap();
  32825. }
  32826. }
  32827. /**
  32828. * The purpose of a node library is to assign node implementations
  32829. * to existing library features. In `WebGPURenderer` lights, materials
  32830. * which are not based on `NodeMaterial` as well as tone mapping techniques
  32831. * are implemented with node-based modules.
  32832. *
  32833. * @private
  32834. */
  32835. class NodeLibrary {
  32836. /**
  32837. * Constructs a new node library.
  32838. */
  32839. constructor() {
  32840. /**
  32841. * A weak map that maps lights to light nodes.
  32842. *
  32843. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  32844. */
  32845. this.lightNodes = new WeakMap();
  32846. /**
  32847. * A map that maps materials to node materials.
  32848. *
  32849. * @type {Map<String,NodeMaterial.constructor>}
  32850. */
  32851. this.materialNodes = new Map();
  32852. /**
  32853. * A map that maps tone mapping techniques (constants)
  32854. * to tone mapping node functions.
  32855. *
  32856. * @type {Map<Number,Function>}
  32857. */
  32858. this.toneMappingNodes = new Map();
  32859. }
  32860. /**
  32861. * Returns a matching node material instance for the given material object.
  32862. *
  32863. * This method also assigns/copies the properties of the given material object
  32864. * to the node material. This is done to make sure the current material
  32865. * configuration carries over to the node version.
  32866. *
  32867. * @param {Material} material - A material.
  32868. * @return {NodeMaterial} The corresponding node material.
  32869. */
  32870. fromMaterial( material ) {
  32871. if ( material.isNodeMaterial ) return material;
  32872. let nodeMaterial = null;
  32873. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  32874. if ( nodeMaterialClass !== null ) {
  32875. nodeMaterial = new nodeMaterialClass();
  32876. for ( const key in material ) {
  32877. nodeMaterial[ key ] = material[ key ];
  32878. }
  32879. }
  32880. return nodeMaterial;
  32881. }
  32882. /**
  32883. * Adds a tone mapping node function for a tone mapping technique (constant).
  32884. *
  32885. * @param {Function} toneMappingNode - The tone mapping node function.
  32886. * @param {Number} toneMapping - The tone mapping.
  32887. */
  32888. addToneMapping( toneMappingNode, toneMapping ) {
  32889. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  32890. }
  32891. /**
  32892. * Returns a tone mapping node function for a tone mapping technique (constant).
  32893. *
  32894. * @param {Number} toneMapping - The tone mapping.
  32895. * @return {Function?} The tone mapping node function. Returns `null` if no node function is found.
  32896. */
  32897. getToneMappingFunction( toneMapping ) {
  32898. return this.toneMappingNodes.get( toneMapping ) || null;
  32899. }
  32900. /**
  32901. * Returns a node material class definition for a material type.
  32902. *
  32903. * @param {String} materialType - The material type.
  32904. * @return {NodeMaterial.constructor?} The node material class definition. Returns `null` if no node material is found.
  32905. */
  32906. getMaterialNodeClass( materialType ) {
  32907. return this.materialNodes.get( materialType ) || null;
  32908. }
  32909. /**
  32910. * Adds a node material class definition for a given material type.
  32911. *
  32912. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  32913. * @param {String} materialClassType - The material type.
  32914. */
  32915. addMaterial( materialNodeClass, materialClassType ) {
  32916. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  32917. }
  32918. /**
  32919. * Returns a light node class definition for a light class definition.
  32920. *
  32921. * @param {Light.constructor} light - The light class definition.
  32922. * @return {AnalyticLightNode.constructor?} The light node class definition. Returns `null` if no light node is found.
  32923. */
  32924. getLightNodeClass( light ) {
  32925. return this.lightNodes.get( light ) || null;
  32926. }
  32927. /**
  32928. * Adds a light node class definition for a given light class definition.
  32929. *
  32930. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  32931. * @param {Light.constructor} lightClass - The light class definition.
  32932. */
  32933. addLight( lightNodeClass, lightClass ) {
  32934. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  32935. }
  32936. /**
  32937. * Adds a node class definition for the given type to the provided type library.
  32938. *
  32939. * @param {Any} nodeClass - The node class definition.
  32940. * @param {Number|String} type - The object type.
  32941. * @param {Map} library - The type library.
  32942. */
  32943. addType( nodeClass, type, library ) {
  32944. if ( library.has( type ) ) {
  32945. console.warn( `Redefinition of node ${ type }` );
  32946. return;
  32947. }
  32948. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32949. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  32950. library.set( type, nodeClass );
  32951. }
  32952. /**
  32953. * Adds a node class definition for the given class definition to the provided type library.
  32954. *
  32955. * @param {Any} nodeClass - The node class definition.
  32956. * @param {Any} baseClass - The class definition.
  32957. * @param {WeakMap} library - The type library.
  32958. */
  32959. addClass( nodeClass, baseClass, library ) {
  32960. if ( library.has( baseClass ) ) {
  32961. console.warn( `Redefinition of node ${ baseClass.name }` );
  32962. return;
  32963. }
  32964. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  32965. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  32966. library.set( baseClass, nodeClass );
  32967. }
  32968. }
  32969. const _defaultLights = /*@__PURE__*/ new LightsNode();
  32970. const _chainKeys = [];
  32971. /**
  32972. * This renderer module manages the lights nodes which are unique
  32973. * per scene and camera combination.
  32974. *
  32975. * The lights node itself is later configured in the render list
  32976. * with the actual lights from the scene.
  32977. *
  32978. * @private
  32979. * @augments ChainMap
  32980. */
  32981. class Lighting extends ChainMap {
  32982. /**
  32983. * Constructs a lighting management component.
  32984. */
  32985. constructor() {
  32986. super();
  32987. }
  32988. /**
  32989. * Creates a new lights node for the given array of lights.
  32990. *
  32991. * @param {Array<Light>} lights - The render object.
  32992. * @return {LightsNode} The lights node.
  32993. */
  32994. createNode( lights = [] ) {
  32995. return new LightsNode().setLights( lights );
  32996. }
  32997. /**
  32998. * Returns a lights node for the given scene and camera.
  32999. *
  33000. * @param {Scene} scene - The scene.
  33001. * @param {Camera} camera - The camera.
  33002. * @return {LightsNode} The lights node.
  33003. */
  33004. getNode( scene, camera ) {
  33005. // ignore post-processing
  33006. if ( scene.isQuadMesh ) return _defaultLights;
  33007. _chainKeys[ 0 ] = scene;
  33008. _chainKeys[ 1 ] = camera;
  33009. let node = this.get( _chainKeys );
  33010. if ( node === undefined ) {
  33011. node = this.createNode();
  33012. this.set( _chainKeys, node );
  33013. }
  33014. _chainKeys.length = 0;
  33015. return node;
  33016. }
  33017. }
  33018. const _cameraLPos = /*@__PURE__*/ new Vector3();
  33019. const _cameraRPos = /*@__PURE__*/ new Vector3();
  33020. /**
  33021. * The XR manager is built on top of the WebXR Device API to
  33022. * manage XR sessions with `WebGPURenderer`.
  33023. *
  33024. * XR is currently only supported with a WebGL 2 backend.
  33025. */
  33026. class XRManager extends EventDispatcher {
  33027. /**
  33028. * Constructs a new XR manager.
  33029. *
  33030. * @param {Renderer} renderer - The renderer.
  33031. */
  33032. constructor( renderer ) {
  33033. super();
  33034. /**
  33035. * This flag globally enables XR rendering.
  33036. *
  33037. * @type {Boolean}
  33038. * @default false
  33039. */
  33040. this.enabled = false;
  33041. /**
  33042. * Whether the XR device is currently presenting or not.
  33043. *
  33044. * @type {Boolean}
  33045. * @default false
  33046. * @readonly
  33047. */
  33048. this.isPresenting = false;
  33049. /**
  33050. * Whether the XR camera should automatically be updated or not.
  33051. *
  33052. * @type {Boolean}
  33053. * @default true
  33054. */
  33055. this.cameraAutoUpdate = true;
  33056. /**
  33057. * The renderer.
  33058. *
  33059. * @private
  33060. * @type {Renderer}
  33061. */
  33062. this._renderer = renderer;
  33063. // camera
  33064. /**
  33065. * Represents the camera for the left eye.
  33066. *
  33067. * @private
  33068. * @type {PerspectiveCamera}
  33069. */
  33070. this._cameraL = new PerspectiveCamera();
  33071. this._cameraL.viewport = new Vector4();
  33072. /**
  33073. * Represents the camera for the right eye.
  33074. *
  33075. * @private
  33076. * @type {PerspectiveCamera}
  33077. */
  33078. this._cameraR = new PerspectiveCamera();
  33079. this._cameraR.viewport = new Vector4();
  33080. /**
  33081. * A list of cameras used for rendering the XR views.
  33082. *
  33083. * @private
  33084. * @type {Array<Camera>}
  33085. */
  33086. this._cameras = [ this._cameraL, this._cameraR ];
  33087. /**
  33088. * The main XR camera.
  33089. *
  33090. * @private
  33091. * @type {ArrayCamera}
  33092. */
  33093. this._cameraXR = new ArrayCamera();
  33094. /**
  33095. * The current near value of the XR camera.
  33096. *
  33097. * @private
  33098. * @type {Number?}
  33099. * @default null
  33100. */
  33101. this._currentDepthNear = null;
  33102. /**
  33103. * The current far value of the XR camera.
  33104. *
  33105. * @private
  33106. * @type {Number?}
  33107. * @default null
  33108. */
  33109. this._currentDepthFar = null;
  33110. /**
  33111. * A list of WebXR controllers requested by the application.
  33112. *
  33113. * @private
  33114. * @type {Array<WebXRController>}
  33115. */
  33116. this._controllers = [];
  33117. /**
  33118. * A list of XR input source. Each input source belongs to
  33119. * an instance of WebXRController.
  33120. *
  33121. * @private
  33122. * @type {Array<XRInputSource?>}
  33123. */
  33124. this._controllerInputSources = [];
  33125. /**
  33126. * The current render target of the renderer.
  33127. *
  33128. * @private
  33129. * @type {RenderTarget?}
  33130. * @default null
  33131. */
  33132. this._currentRenderTarget = null;
  33133. /**
  33134. * The XR render target that represents the rendering destination
  33135. * during an active XR session.
  33136. *
  33137. * @private
  33138. * @type {RenderTarget?}
  33139. * @default null
  33140. */
  33141. this._xrRenderTarget = null;
  33142. /**
  33143. * The current animation context.
  33144. *
  33145. * @private
  33146. * @type {Window?}
  33147. * @default null
  33148. */
  33149. this._currentAnimationContext = null;
  33150. /**
  33151. * The current animation loop.
  33152. *
  33153. * @private
  33154. * @type {Function?}
  33155. * @default null
  33156. */
  33157. this._currentAnimationLoop = null;
  33158. /**
  33159. * The current pixel ratio.
  33160. *
  33161. * @private
  33162. * @type {Number?}
  33163. * @default null
  33164. */
  33165. this._currentPixelRatio = null;
  33166. /**
  33167. * The current size of the renderer's canvas
  33168. * in logical pixel unit.
  33169. *
  33170. * @private
  33171. * @type {Vector2}
  33172. */
  33173. this._currentSize = new Vector2();
  33174. /**
  33175. * The default event listener for handling events inside a XR session.
  33176. *
  33177. * @private
  33178. * @type {Function}
  33179. */
  33180. this._onSessionEvent = onSessionEvent.bind( this );
  33181. /**
  33182. * The event listener for handling the end of a XR session.
  33183. *
  33184. * @private
  33185. * @type {Function}
  33186. */
  33187. this._onSessionEnd = onSessionEnd.bind( this );
  33188. /**
  33189. * The event listener for handling the `inputsourceschange` event.
  33190. *
  33191. * @private
  33192. * @type {Function}
  33193. */
  33194. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  33195. /**
  33196. * The animation loop which is used as a replacement for the default
  33197. * animation loop of the applicatio. It is only used when a XR session
  33198. * is active.
  33199. *
  33200. * @private
  33201. * @type {Function}
  33202. */
  33203. this._onAnimationFrame = onAnimationFrame.bind( this );
  33204. /**
  33205. * The current XR reference space.
  33206. *
  33207. * @private
  33208. * @type {XRReferenceSpace?}
  33209. * @default null
  33210. */
  33211. this._referenceSpace = null;
  33212. /**
  33213. * The current XR reference space type.
  33214. *
  33215. * @private
  33216. * @type {String}
  33217. * @default 'local-floor'
  33218. */
  33219. this._referenceSpaceType = 'local-floor';
  33220. /**
  33221. * A custom reference space defined by the application.
  33222. *
  33223. * @private
  33224. * @type {XRReferenceSpace?}
  33225. * @default null
  33226. */
  33227. this._customReferenceSpace = null;
  33228. /**
  33229. * The framebuffer scale factor.
  33230. *
  33231. * @private
  33232. * @type {Number}
  33233. * @default 1
  33234. */
  33235. this._framebufferScaleFactor = 1;
  33236. /**
  33237. * The foveation factor.
  33238. *
  33239. * @private
  33240. * @type {Number}
  33241. * @default 1
  33242. */
  33243. this._foveation = 1.0;
  33244. /**
  33245. * A reference to the current XR session.
  33246. *
  33247. * @private
  33248. * @type {XRSession?}
  33249. * @default null
  33250. */
  33251. this._session = null;
  33252. /**
  33253. * A reference to the current XR base layer.
  33254. *
  33255. * @private
  33256. * @type {XRWebGLLayer?}
  33257. * @default null
  33258. */
  33259. this._glBaseLayer = null;
  33260. /**
  33261. * A reference to the current XR frame.
  33262. *
  33263. * @private
  33264. * @type {XRFrame?}
  33265. * @default null
  33266. */
  33267. this._xrFrame = null;
  33268. }
  33269. /**
  33270. * Returns an instance of `THREE.Group` that represents the transformation
  33271. * of a XR controller in target ray space. The requested controller is defined
  33272. * by the given index.
  33273. *
  33274. * @param {Number} index - The index of the XR controller.
  33275. * @return {Group} A group that represents the controller's transformation.
  33276. */
  33277. getController( index ) {
  33278. const controller = this._getController( index );
  33279. return controller.getTargetRaySpace();
  33280. }
  33281. /**
  33282. * Returns an instance of `THREE.Group` that represents the transformation
  33283. * of a XR controller in grip space. The requested controller is defined
  33284. * by the given index.
  33285. *
  33286. * @param {Number} index - The index of the XR controller.
  33287. * @return {Group} A group that represents the controller's transformation.
  33288. */
  33289. getControllerGrip( index ) {
  33290. const controller = this._getController( index );
  33291. return controller.getGripSpace();
  33292. }
  33293. /**
  33294. * Returns an instance of `THREE.Group` that represents the transformation
  33295. * of a XR controller in hand space. The requested controller is defined
  33296. * by the given index.
  33297. *
  33298. * @param {Number} index - The index of the XR controller.
  33299. * @return {Group} A group that represents the controller's transformation.
  33300. */
  33301. getHand( index ) {
  33302. const controller = this._getController( index );
  33303. return controller.getHandSpace();
  33304. }
  33305. /**
  33306. * Returns the foveation value.
  33307. *
  33308. * @return {Number|undefined} The foveation value. Returns `undefined` if no base layer is defined.
  33309. */
  33310. getFoveation() {
  33311. if ( this._glBaseLayer === null ) {
  33312. return undefined;
  33313. }
  33314. return this._foveation;
  33315. }
  33316. /**
  33317. * Sets the foveation value.
  33318. *
  33319. * @param {Number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  33320. * and `1` means maximum foveation (the edges render at lower resolution).
  33321. */
  33322. setFoveation( foveation ) {
  33323. this._foveation = foveation;
  33324. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  33325. this._glBaseLayer.fixedFoveation = foveation;
  33326. }
  33327. }
  33328. /**
  33329. * Returns the frammebuffer scale factor.
  33330. *
  33331. * @return {Number} The frammebuffer scale factor.
  33332. */
  33333. getFramebufferScaleFactor() {
  33334. return this._framebufferScaleFactor;
  33335. }
  33336. /**
  33337. * Sets the frammebuffer scale factor.
  33338. *
  33339. * This method can not be used during a XR session.
  33340. *
  33341. * @param {Number} factor - The frammebuffer scale factor.
  33342. */
  33343. setFramebufferScaleFactor( factor ) {
  33344. this._framebufferScaleFactor = factor;
  33345. if ( this.isPresenting === true ) {
  33346. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  33347. }
  33348. }
  33349. /**
  33350. * Returns the reference space type.
  33351. *
  33352. * @return {String} The reference space type.
  33353. */
  33354. getReferenceSpaceType() {
  33355. return this._referenceSpaceType;
  33356. }
  33357. /**
  33358. * Sets the reference space type.
  33359. *
  33360. * This method can not be used during a XR session.
  33361. *
  33362. * @param {String} type - The reference space type.
  33363. */
  33364. setReferenceSpaceType( type ) {
  33365. this._referenceSpaceType = type;
  33366. if ( this.isPresenting === true ) {
  33367. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  33368. }
  33369. }
  33370. /**
  33371. * Returns the XR reference space.
  33372. *
  33373. * @return {XRReferenceSpace} The XR reference space.
  33374. */
  33375. getReferenceSpace() {
  33376. return this._customReferenceSpace || this._referenceSpace;
  33377. }
  33378. /**
  33379. * Sets a custom XR reference space.
  33380. *
  33381. * @param {XRReferenceSpace} space - The XR reference space.
  33382. */
  33383. setReferenceSpace( space ) {
  33384. this._customReferenceSpace = space;
  33385. }
  33386. /**
  33387. * Returns the XR camera.
  33388. *
  33389. * @return {ArrayCamera} The XR camera.
  33390. */
  33391. getCamera() {
  33392. return this._cameraXR;
  33393. }
  33394. /**
  33395. * Returns the environment blend mode from the current XR session.
  33396. *
  33397. * @return {'opaque'|'additive'|'alpha-blend'} The environment blend mode.
  33398. */
  33399. getEnvironmentBlendMode() {
  33400. if ( this._session !== null ) {
  33401. return this._session.environmentBlendMode;
  33402. }
  33403. }
  33404. /**
  33405. * Returns the current XR frame.
  33406. *
  33407. * @return {XRFrame?} The XR frame. Returns `null` when used outside a XR session.
  33408. */
  33409. getFrame() {
  33410. return this._xrFrame;
  33411. }
  33412. /**
  33413. * Returns the current XR session.
  33414. *
  33415. * @return {XRSession?} The XR session. Returns `null` when used outside a XR session.
  33416. */
  33417. getSession() {
  33418. return this._session;
  33419. }
  33420. /**
  33421. * After a XR session has been requested usually with one of the `*Button` modules, it
  33422. * is injected into the renderer with this method. This method triggers the start of
  33423. * the actual XR rendering.
  33424. *
  33425. * @async
  33426. * @param {XRSession} session - The XR session to set.
  33427. * @return {Promise} A Promise that resolves when the session has been set.
  33428. */
  33429. async setSession( session ) {
  33430. const renderer = this._renderer;
  33431. const gl = renderer.getContext();
  33432. this._session = session;
  33433. if ( session !== null ) {
  33434. if ( renderer.backend.isWebGPUBackend === true ) throw new Error( 'THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.' );
  33435. this._currentRenderTarget = renderer.getRenderTarget();
  33436. session.addEventListener( 'select', this._onSessionEvent );
  33437. session.addEventListener( 'selectstart', this._onSessionEvent );
  33438. session.addEventListener( 'selectend', this._onSessionEvent );
  33439. session.addEventListener( 'squeeze', this._onSessionEvent );
  33440. session.addEventListener( 'squeezestart', this._onSessionEvent );
  33441. session.addEventListener( 'squeezeend', this._onSessionEvent );
  33442. session.addEventListener( 'end', this._onSessionEnd );
  33443. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  33444. await renderer.makeXRCompatible();
  33445. this._currentPixelRatio = renderer.getPixelRatio();
  33446. renderer.getSize( this._currentSize );
  33447. this._currentAnimationContext = renderer._animation.getContext();
  33448. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  33449. renderer._animation.stop();
  33450. const attributes = gl.getContextAttributes();
  33451. const layerInit = {
  33452. antialias: attributes.antialias,
  33453. alpha: true,
  33454. depth: attributes.depth,
  33455. stencil: attributes.stencil,
  33456. framebufferScaleFactor: this.getFramebufferScaleFactor()
  33457. };
  33458. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  33459. this._glBaseLayer = glBaseLayer;
  33460. session.updateRenderState( { baseLayer: glBaseLayer } );
  33461. renderer.setPixelRatio( 1 );
  33462. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  33463. this._xrRenderTarget = new RenderTarget(
  33464. glBaseLayer.framebufferWidth,
  33465. glBaseLayer.framebufferHeight,
  33466. {
  33467. format: RGBAFormat,
  33468. type: UnsignedByteType,
  33469. colorSpace: renderer.outputColorSpace,
  33470. stencilBuffer: attributes.stencil
  33471. }
  33472. );
  33473. this._xrRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  33474. this.setFoveation( this.getFoveation() );
  33475. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  33476. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  33477. renderer._animation.setContext( session );
  33478. renderer._animation.start();
  33479. this.isPresenting = true;
  33480. this.dispatchEvent( { type: 'sessionstart' } );
  33481. }
  33482. }
  33483. /**
  33484. * This method is called by the renderer per frame and updates the XR camera
  33485. * and it sub cameras based on the given camera. The given camera is the "normal"
  33486. * camera created on application level and used for non-XR rendering.
  33487. *
  33488. * @param {PerspectiveCamera} camera - The camera.
  33489. */
  33490. updateCamera( camera ) {
  33491. const session = this._session;
  33492. if ( session === null ) return;
  33493. const depthNear = camera.near;
  33494. const depthFar = camera.far;
  33495. const cameraXR = this._cameraXR;
  33496. const cameraL = this._cameraL;
  33497. const cameraR = this._cameraR;
  33498. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  33499. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  33500. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  33501. // Note that the new renderState won't apply until the next frame. See #18320
  33502. session.updateRenderState( {
  33503. depthNear: cameraXR.near,
  33504. depthFar: cameraXR.far
  33505. } );
  33506. this._currentDepthNear = cameraXR.near;
  33507. this._currentDepthFar = cameraXR.far;
  33508. }
  33509. cameraL.layers.mask = camera.layers.mask | 0b010;
  33510. cameraR.layers.mask = camera.layers.mask | 0b100;
  33511. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  33512. const parent = camera.parent;
  33513. const cameras = cameraXR.cameras;
  33514. updateCamera( cameraXR, parent );
  33515. for ( let i = 0; i < cameras.length; i ++ ) {
  33516. updateCamera( cameras[ i ], parent );
  33517. }
  33518. // update projection matrix for proper view frustum culling
  33519. if ( cameras.length === 2 ) {
  33520. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  33521. } else {
  33522. // assume single camera setup (AR)
  33523. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  33524. }
  33525. // update user camera and its children
  33526. updateUserCamera( camera, cameraXR, parent );
  33527. }
  33528. /**
  33529. * Returns a WebXR controller for the given controller index.
  33530. *
  33531. * @private
  33532. * @param {Number} index - The controller index.
  33533. * @return {WebXRController} The XR controller.
  33534. */
  33535. _getController( index ) {
  33536. let controller = this._controllers[ index ];
  33537. if ( controller === undefined ) {
  33538. controller = new WebXRController();
  33539. this._controllers[ index ] = controller;
  33540. }
  33541. return controller;
  33542. }
  33543. }
  33544. /**
  33545. * Assumes 2 cameras that are parallel and share an X-axis, and that
  33546. * the cameras' projection and world matrices have already been set.
  33547. * And that near and far planes are identical for both cameras.
  33548. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  33549. *
  33550. * @param {ArrayCamera} camera - The camera to update.
  33551. * @param {PerspectiveCamera} cameraL - The left camera.
  33552. * @param {PerspectiveCamera} cameraR - The right camera.
  33553. */
  33554. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  33555. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  33556. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  33557. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  33558. const projL = cameraL.projectionMatrix.elements;
  33559. const projR = cameraR.projectionMatrix.elements;
  33560. // VR systems will have identical far and near planes, and
  33561. // most likely identical top and bottom frustum extents.
  33562. // Use the left camera for these values.
  33563. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  33564. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  33565. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  33566. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  33567. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  33568. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  33569. const left = near * leftFov;
  33570. const right = near * rightFov;
  33571. // Calculate the new camera's position offset from the
  33572. // left camera. xOffset should be roughly half `ipd`.
  33573. const zOffset = ipd / ( - leftFov + rightFov );
  33574. const xOffset = zOffset * - leftFov;
  33575. // TODO: Better way to apply this offset?
  33576. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  33577. camera.translateX( xOffset );
  33578. camera.translateZ( zOffset );
  33579. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  33580. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  33581. // Check if the projection uses an infinite far plane.
  33582. if ( projL[ 10 ] === - 1.0 ) {
  33583. // Use the projection matrix from the left eye.
  33584. // The camera offset is sufficient to include the view volumes
  33585. // of both eyes (assuming symmetric projections).
  33586. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  33587. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  33588. } else {
  33589. // Find the union of the frustum values of the cameras and scale
  33590. // the values so that the near plane's position does not change in world space,
  33591. // although must now be relative to the new union camera.
  33592. const near2 = near + zOffset;
  33593. const far2 = far + zOffset;
  33594. const left2 = left - xOffset;
  33595. const right2 = right + ( ipd - xOffset );
  33596. const top2 = topFov * far / far2 * near2;
  33597. const bottom2 = bottomFov * far / far2 * near2;
  33598. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  33599. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  33600. }
  33601. }
  33602. /**
  33603. * Updates the world matrices for the given camera based on the parent 3D object.
  33604. *
  33605. * @inner
  33606. * @param {Camera} camera - The camera to update.
  33607. * @param {Object3D} parent - The parent 3D object.
  33608. */
  33609. function updateCamera( camera, parent ) {
  33610. if ( parent === null ) {
  33611. camera.matrixWorld.copy( camera.matrix );
  33612. } else {
  33613. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  33614. }
  33615. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  33616. }
  33617. /**
  33618. * Updates the given camera with the transfomration of the XR camera and parent object.
  33619. *
  33620. * @inner
  33621. * @param {Camera} camera - The camera to update.
  33622. * @param {ArrayCamera} cameraXR - The XR camera.
  33623. * @param {Object3D} parent - The parent 3D object.
  33624. */
  33625. function updateUserCamera( camera, cameraXR, parent ) {
  33626. if ( parent === null ) {
  33627. camera.matrix.copy( cameraXR.matrixWorld );
  33628. } else {
  33629. camera.matrix.copy( parent.matrixWorld );
  33630. camera.matrix.invert();
  33631. camera.matrix.multiply( cameraXR.matrixWorld );
  33632. }
  33633. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  33634. camera.updateMatrixWorld( true );
  33635. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  33636. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  33637. if ( camera.isPerspectiveCamera ) {
  33638. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  33639. camera.zoom = 1;
  33640. }
  33641. }
  33642. function onSessionEvent( event ) {
  33643. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  33644. if ( controllerIndex === - 1 ) {
  33645. return;
  33646. }
  33647. const controller = this._controllers[ controllerIndex ];
  33648. if ( controller !== undefined ) {
  33649. const referenceSpace = this.getReferenceSpace();
  33650. controller.update( event.inputSource, event.frame, referenceSpace );
  33651. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  33652. }
  33653. }
  33654. function onSessionEnd() {
  33655. const session = this._session;
  33656. const renderer = this._renderer;
  33657. session.removeEventListener( 'select', this._onSessionEvent );
  33658. session.removeEventListener( 'selectstart', this._onSessionEvent );
  33659. session.removeEventListener( 'selectend', this._onSessionEvent );
  33660. session.removeEventListener( 'squeeze', this._onSessionEvent );
  33661. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  33662. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  33663. session.removeEventListener( 'end', this._onSessionEnd );
  33664. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  33665. for ( let i = 0; i < this._controllers.length; i ++ ) {
  33666. const inputSource = this._controllerInputSources[ i ];
  33667. if ( inputSource === null ) continue;
  33668. this._controllerInputSources[ i ] = null;
  33669. this._controllers[ i ].disconnect( inputSource );
  33670. }
  33671. this._currentDepthNear = null;
  33672. this._currentDepthFar = null;
  33673. // restore framebuffer/rendering state
  33674. renderer.setRenderTarget( this._currentRenderTarget );
  33675. this._session = null;
  33676. this._xrRenderTarget = null;
  33677. //
  33678. this.isPresenting = false;
  33679. renderer._animation.stop();
  33680. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  33681. renderer._animation.setContext( this._currentAnimationContext );
  33682. renderer._animation.start();
  33683. renderer.setPixelRatio( this._currentPixelRatio );
  33684. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  33685. renderer.setXRTarget( null );
  33686. this.dispatchEvent( { type: 'sessionend' } );
  33687. }
  33688. function onInputSourcesChange( event ) {
  33689. const controllers = this._controllers;
  33690. const controllerInputSources = this._controllerInputSources;
  33691. // Notify disconnected
  33692. for ( let i = 0; i < event.removed.length; i ++ ) {
  33693. const inputSource = event.removed[ i ];
  33694. const index = controllerInputSources.indexOf( inputSource );
  33695. if ( index >= 0 ) {
  33696. controllerInputSources[ index ] = null;
  33697. controllers[ index ].disconnect( inputSource );
  33698. }
  33699. }
  33700. // Notify connected
  33701. for ( let i = 0; i < event.added.length; i ++ ) {
  33702. const inputSource = event.added[ i ];
  33703. let controllerIndex = controllerInputSources.indexOf( inputSource );
  33704. if ( controllerIndex === - 1 ) {
  33705. // Assign input source a controller that currently has no input source
  33706. for ( let i = 0; i < controllers.length; i ++ ) {
  33707. if ( i >= controllerInputSources.length ) {
  33708. controllerInputSources.push( inputSource );
  33709. controllerIndex = i;
  33710. break;
  33711. } else if ( controllerInputSources[ i ] === null ) {
  33712. controllerInputSources[ i ] = inputSource;
  33713. controllerIndex = i;
  33714. break;
  33715. }
  33716. }
  33717. // If all controllers do currently receive input we ignore new ones
  33718. if ( controllerIndex === - 1 ) break;
  33719. }
  33720. const controller = controllers[ controllerIndex ];
  33721. if ( controller ) {
  33722. controller.connect( inputSource );
  33723. }
  33724. }
  33725. }
  33726. function onAnimationFrame( time, frame ) {
  33727. if ( frame === undefined ) return;
  33728. const cameraXR = this._cameraXR;
  33729. const renderer = this._renderer;
  33730. const glBaseLayer = this._glBaseLayer;
  33731. const referenceSpace = this.getReferenceSpace();
  33732. const pose = frame.getViewerPose( referenceSpace );
  33733. this._xrFrame = frame;
  33734. if ( pose !== null ) {
  33735. const views = pose.views;
  33736. renderer.setXRTarget( glBaseLayer.framebuffer );
  33737. renderer.setRenderTarget( this._xrRenderTarget );
  33738. let cameraXRNeedsUpdate = false;
  33739. // check if it's necessary to rebuild cameraXR's camera list
  33740. if ( views.length !== cameraXR.cameras.length ) {
  33741. cameraXR.cameras.length = 0;
  33742. cameraXRNeedsUpdate = true;
  33743. }
  33744. for ( let i = 0; i < views.length; i ++ ) {
  33745. const view = views[ i ];
  33746. const viewport = glBaseLayer.getViewport( view );
  33747. let camera = this._cameras[ i ];
  33748. if ( camera === undefined ) {
  33749. camera = new PerspectiveCamera();
  33750. camera.layers.enable( i );
  33751. camera.viewport = new Vector4();
  33752. this._cameras[ i ] = camera;
  33753. }
  33754. camera.matrix.fromArray( view.transform.matrix );
  33755. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  33756. camera.projectionMatrix.fromArray( view.projectionMatrix );
  33757. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  33758. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  33759. if ( i === 0 ) {
  33760. cameraXR.matrix.copy( camera.matrix );
  33761. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  33762. }
  33763. if ( cameraXRNeedsUpdate === true ) {
  33764. cameraXR.cameras.push( camera );
  33765. }
  33766. }
  33767. }
  33768. //
  33769. for ( let i = 0; i < this._controllers.length; i ++ ) {
  33770. const inputSource = this._controllerInputSources[ i ];
  33771. const controller = this._controllers[ i ];
  33772. if ( inputSource !== null && controller !== undefined ) {
  33773. controller.update( inputSource, frame, referenceSpace );
  33774. }
  33775. }
  33776. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  33777. if ( frame.detectedPlanes ) {
  33778. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  33779. }
  33780. this._xrFrame = null;
  33781. }
  33782. /** @module Renderer **/
  33783. const _scene = /*@__PURE__*/ new Scene();
  33784. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  33785. const _screen = /*@__PURE__*/ new Vector4();
  33786. const _frustum = /*@__PURE__*/ new Frustum();
  33787. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33788. const _vector4 = /*@__PURE__*/ new Vector4();
  33789. /**
  33790. * Base class for renderers.
  33791. */
  33792. class Renderer {
  33793. /**
  33794. * Constructs a new renderer.
  33795. *
  33796. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  33797. * @param {Object} parameters - The configuration parameter.
  33798. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  33799. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  33800. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  33801. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  33802. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  33803. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. This parameter can set to any other integer value than 0
  33804. * to overwrite the default.
  33805. * @param {Function?} [parameters.getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  33806. */
  33807. constructor( backend, parameters = {} ) {
  33808. /**
  33809. * This flag can be used for type testing.
  33810. *
  33811. * @type {Boolean}
  33812. * @readonly
  33813. * @default true
  33814. */
  33815. this.isRenderer = true;
  33816. //
  33817. const {
  33818. logarithmicDepthBuffer = false,
  33819. alpha = true,
  33820. depth = true,
  33821. stencil = false,
  33822. antialias = false,
  33823. samples = 0,
  33824. getFallback = null
  33825. } = parameters;
  33826. /**
  33827. * A reference to the canvas element the renderer is drawing to.
  33828. * This value of this property will automatically be created by
  33829. * the renderer.
  33830. *
  33831. * @type {HTMLCanvasElement|OffscreenCanvas}
  33832. */
  33833. this.domElement = backend.getDomElement();
  33834. /**
  33835. * A reference to the current backend.
  33836. *
  33837. * @type {Backend}
  33838. */
  33839. this.backend = backend;
  33840. /**
  33841. * The number of MSAA samples.
  33842. *
  33843. * @type {Number}
  33844. * @default 0
  33845. */
  33846. this.samples = samples || ( antialias === true ) ? 4 : 0;
  33847. /**
  33848. * Whether the renderer should automatically clear the current rendering target
  33849. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  33850. * or the current bound render target (custom framebuffer).
  33851. *
  33852. * @type {Boolean}
  33853. * @default true
  33854. */
  33855. this.autoClear = true;
  33856. /**
  33857. * When `autoClear` is set to `true`, this property defines whether the renderer
  33858. * should clear the color buffer.
  33859. *
  33860. * @type {Boolean}
  33861. * @default true
  33862. */
  33863. this.autoClearColor = true;
  33864. /**
  33865. * When `autoClear` is set to `true`, this property defines whether the renderer
  33866. * should clear the depth buffer.
  33867. *
  33868. * @type {Boolean}
  33869. * @default true
  33870. */
  33871. this.autoClearDepth = true;
  33872. /**
  33873. * When `autoClear` is set to `true`, this property defines whether the renderer
  33874. * should clear the stencil buffer.
  33875. *
  33876. * @type {Boolean}
  33877. * @default true
  33878. */
  33879. this.autoClearStencil = true;
  33880. /**
  33881. * Whether the default framebuffer should be transparent or opaque.
  33882. *
  33883. * @type {Boolean}
  33884. * @default true
  33885. */
  33886. this.alpha = alpha;
  33887. /**
  33888. * Whether logarithmic depth buffer is enabled or not.
  33889. *
  33890. * @type {Boolean}
  33891. * @default false
  33892. */
  33893. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  33894. /**
  33895. * Defines the output color space of the renderer.
  33896. *
  33897. * @type {String}
  33898. * @default SRGBColorSpace
  33899. */
  33900. this.outputColorSpace = SRGBColorSpace;
  33901. /**
  33902. * Defines the tone mapping of the renderer.
  33903. *
  33904. * @type {Number}
  33905. * @default NoToneMapping
  33906. */
  33907. this.toneMapping = NoToneMapping;
  33908. /**
  33909. * Defines the tone mapping exposure.
  33910. *
  33911. * @type {Number}
  33912. * @default 1
  33913. */
  33914. this.toneMappingExposure = 1.0;
  33915. /**
  33916. * Whether the renderer should sort its render lists or not.
  33917. *
  33918. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  33919. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  33920. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  33921. * e.g. manually determining each object's rendering order.
  33922. *
  33923. * @type {Boolean}
  33924. * @default true
  33925. */
  33926. this.sortObjects = true;
  33927. /**
  33928. * Whether the default framebuffer should have a depth buffer or not.
  33929. *
  33930. * @type {Boolean}
  33931. * @default true
  33932. */
  33933. this.depth = depth;
  33934. /**
  33935. * Whether the default framebuffer should have a stencil buffer or not.
  33936. *
  33937. * @type {Boolean}
  33938. * @default false
  33939. */
  33940. this.stencil = stencil;
  33941. /**
  33942. * Holds a series of statistical information about the GPU memory
  33943. * and the rendering process. Useful for debugging and monitoring.
  33944. *
  33945. * @type {Info}
  33946. */
  33947. this.info = new Info();
  33948. this.nodes = {
  33949. modelViewMatrix: null,
  33950. modelNormalViewMatrix: null
  33951. };
  33952. /**
  33953. * The node library defines how certain library objects like materials, lights
  33954. * or tone mapping functions are mapped to node types. This is required since
  33955. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  33956. * be part of the scene graph, they are internally represented as nodes for
  33957. * further processing.
  33958. *
  33959. * @type {NodeLibrary}
  33960. */
  33961. this.library = new NodeLibrary();
  33962. /**
  33963. * A map-like data structure for managing lights.
  33964. *
  33965. * @type {Lighting}
  33966. */
  33967. this.lighting = new Lighting();
  33968. // internals
  33969. /**
  33970. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  33971. *
  33972. * @private
  33973. * @type {Function}
  33974. */
  33975. this._getFallback = getFallback;
  33976. /**
  33977. * The renderer's pixel ration.
  33978. *
  33979. * @private
  33980. * @type {Number}
  33981. * @default 1
  33982. */
  33983. this._pixelRatio = 1;
  33984. /**
  33985. * The width of the renderer's default framebuffer in logical pixel unit.
  33986. *
  33987. * @private
  33988. * @type {Number}
  33989. */
  33990. this._width = this.domElement.width;
  33991. /**
  33992. * The height of the renderer's default framebuffer in logical pixel unit.
  33993. *
  33994. * @private
  33995. * @type {Number}
  33996. */
  33997. this._height = this.domElement.height;
  33998. /**
  33999. * The viewport of the renderer in logical pixel unit.
  34000. *
  34001. * @private
  34002. * @type {Vector4}
  34003. */
  34004. this._viewport = new Vector4( 0, 0, this._width, this._height );
  34005. /**
  34006. * The scissor rectangle of the renderer in logical pixel unit.
  34007. *
  34008. * @private
  34009. * @type {Vector4}
  34010. */
  34011. this._scissor = new Vector4( 0, 0, this._width, this._height );
  34012. /**
  34013. * Whether the scissor test should be enabled or not.
  34014. *
  34015. * @private
  34016. * @type {Boolean}
  34017. */
  34018. this._scissorTest = false;
  34019. /**
  34020. * A reference to a renderer module for managing shader attributes.
  34021. *
  34022. * @private
  34023. * @type {Attributes?}
  34024. * @default null
  34025. */
  34026. this._attributes = null;
  34027. /**
  34028. * A reference to a renderer module for managing geometries.
  34029. *
  34030. * @private
  34031. * @type {Geometries?}
  34032. * @default null
  34033. */
  34034. this._geometries = null;
  34035. /**
  34036. * A reference to a renderer module for managing node related logic.
  34037. *
  34038. * @private
  34039. * @type {Nodes?}
  34040. * @default null
  34041. */
  34042. this._nodes = null;
  34043. /**
  34044. * A reference to a renderer module for managing the internal animation loop.
  34045. *
  34046. * @private
  34047. * @type {Animation?}
  34048. * @default null
  34049. */
  34050. this._animation = null;
  34051. /**
  34052. * A reference to a renderer module for managing shader program bindings.
  34053. *
  34054. * @private
  34055. * @type {Bindings?}
  34056. * @default null
  34057. */
  34058. this._bindings = null;
  34059. /**
  34060. * A reference to a renderer module for managing render objects.
  34061. *
  34062. * @private
  34063. * @type {RenderObjects?}
  34064. * @default null
  34065. */
  34066. this._objects = null;
  34067. /**
  34068. * A reference to a renderer module for managing render and compute pipelines.
  34069. *
  34070. * @private
  34071. * @type {Pipelines?}
  34072. * @default null
  34073. */
  34074. this._pipelines = null;
  34075. /**
  34076. * A reference to a renderer module for managing render bundles.
  34077. *
  34078. * @private
  34079. * @type {RenderBundles?}
  34080. * @default null
  34081. */
  34082. this._bundles = null;
  34083. /**
  34084. * A reference to a renderer module for managing render lists.
  34085. *
  34086. * @private
  34087. * @type {RenderLists?}
  34088. * @default null
  34089. */
  34090. this._renderLists = null;
  34091. /**
  34092. * A reference to a renderer module for managing render contexts.
  34093. *
  34094. * @private
  34095. * @type {RenderContexts?}
  34096. * @default null
  34097. */
  34098. this._renderContexts = null;
  34099. /**
  34100. * A reference to a renderer module for managing textures.
  34101. *
  34102. * @private
  34103. * @type {Textures?}
  34104. * @default null
  34105. */
  34106. this._textures = null;
  34107. /**
  34108. * A reference to a renderer module for backgrounds.
  34109. *
  34110. * @private
  34111. * @type {Background?}
  34112. * @default null
  34113. */
  34114. this._background = null;
  34115. /**
  34116. * This fullscreen quad is used for internal render passes
  34117. * like the tone mapping and color space output pass.
  34118. *
  34119. * @private
  34120. * @type {QuadMesh}
  34121. */
  34122. this._quad = new QuadMesh( new NodeMaterial() );
  34123. this._quad.material.name = 'Renderer_output';
  34124. /**
  34125. * A reference to the current render context.
  34126. *
  34127. * @private
  34128. * @type {RenderContext?}
  34129. * @default null
  34130. */
  34131. this._currentRenderContext = null;
  34132. /**
  34133. * A custom sort function for the opaque render list.
  34134. *
  34135. * @private
  34136. * @type {Function?}
  34137. * @default null
  34138. */
  34139. this._opaqueSort = null;
  34140. /**
  34141. * A custom sort function for the transparent render list.
  34142. *
  34143. * @private
  34144. * @type {Function?}
  34145. * @default null
  34146. */
  34147. this._transparentSort = null;
  34148. /**
  34149. * The framebuffer target.
  34150. *
  34151. * @private
  34152. * @type {RenderTarget?}
  34153. * @default null
  34154. */
  34155. this._frameBufferTarget = null;
  34156. const alphaClear = this.alpha === true ? 0 : 1;
  34157. /**
  34158. * The clear color value.
  34159. *
  34160. * @private
  34161. * @type {Color4}
  34162. */
  34163. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  34164. /**
  34165. * The clear depth value.
  34166. *
  34167. * @private
  34168. * @type {Number}
  34169. * @default 1
  34170. */
  34171. this._clearDepth = 1;
  34172. /**
  34173. * The clear stencil value.
  34174. *
  34175. * @private
  34176. * @type {Number}
  34177. * @default 0
  34178. */
  34179. this._clearStencil = 0;
  34180. /**
  34181. * The current render target.
  34182. *
  34183. * @private
  34184. * @type {RenderTarget?}
  34185. * @default null
  34186. */
  34187. this._renderTarget = null;
  34188. /**
  34189. * The active cube face.
  34190. *
  34191. * @private
  34192. * @type {Number}
  34193. * @default 0
  34194. */
  34195. this._activeCubeFace = 0;
  34196. /**
  34197. * The active mipmap level.
  34198. *
  34199. * @private
  34200. * @type {Number}
  34201. * @default 0
  34202. */
  34203. this._activeMipmapLevel = 0;
  34204. /**
  34205. * The MRT setting.
  34206. *
  34207. * @private
  34208. * @type {MRTNode?}
  34209. * @default null
  34210. */
  34211. this._mrt = null;
  34212. /**
  34213. * This function defines how a render object is going
  34214. * to be rendered.
  34215. *
  34216. * @private
  34217. * @type {Function?}
  34218. * @default null
  34219. */
  34220. this._renderObjectFunction = null;
  34221. /**
  34222. * Used to keep track of the current render object function.
  34223. *
  34224. * @private
  34225. * @type {Function?}
  34226. * @default null
  34227. */
  34228. this._currentRenderObjectFunction = null;
  34229. /**
  34230. * Used to keep track of the current render bundle.
  34231. *
  34232. * @private
  34233. * @type {RenderBundle?}
  34234. * @default null
  34235. */
  34236. this._currentRenderBundle = null;
  34237. /**
  34238. * Next to `_renderObjectFunction()`, this function provides another hook
  34239. * for influencing the render process of a render object. It is meant for internal
  34240. * use and only relevant for `compileAsync()` right now. Instead of using
  34241. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  34242. * a different function might be used which performs no draw but just the node
  34243. * and pipeline updates.
  34244. *
  34245. * @private
  34246. * @type {Function?}
  34247. * @default null
  34248. */
  34249. this._handleObjectFunction = this._renderObjectDirect;
  34250. /**
  34251. * Indicates whether the device has been lost or not. In WebGL terms, the device
  34252. * lost is considered as a context lost. When this is set to `true`, rendering
  34253. * isn't possible anymore.
  34254. *
  34255. * @private
  34256. * @type {Boolean}
  34257. * @default false
  34258. */
  34259. this._isDeviceLost = false;
  34260. /**
  34261. * A callback function that defines what should happen when a device/context lost occurs.
  34262. *
  34263. * @type {Function}
  34264. */
  34265. this.onDeviceLost = this._onDeviceLost;
  34266. /**
  34267. * Whether the renderer has been initialized or not.
  34268. *
  34269. * @private
  34270. * @type {Boolean}
  34271. * @default false
  34272. */
  34273. this._initialized = false;
  34274. /**
  34275. * A reference to the promise which initializes the renderer.
  34276. *
  34277. * @private
  34278. * @type {Promise?}
  34279. * @default null
  34280. */
  34281. this._initPromise = null;
  34282. /**
  34283. * An array of compilation promises which are used in `compileAsync()`.
  34284. *
  34285. * @private
  34286. * @type {Array<Promise>?}
  34287. * @default null
  34288. */
  34289. this._compilationPromises = null;
  34290. /**
  34291. * Whether the renderer should render transparent render objects or not.
  34292. *
  34293. * @type {Boolean}
  34294. * @default true
  34295. */
  34296. this.transparent = true;
  34297. /**
  34298. * Whether the renderer should render opaque render objects or not.
  34299. *
  34300. * @type {Boolean}
  34301. * @default true
  34302. */
  34303. this.opaque = true;
  34304. /**
  34305. * Shadow map configuration
  34306. * @typedef {Object} ShadowMapConfig
  34307. * @property {Boolean} enabled - Whether to globally enable shadows or not.
  34308. * @property {Number} type - The shadow map type.
  34309. */
  34310. /**
  34311. * The renderer's shadow configuration.
  34312. *
  34313. * @type {module:Renderer~ShadowMapConfig}
  34314. */
  34315. this.shadowMap = {
  34316. enabled: false,
  34317. type: PCFShadowMap
  34318. };
  34319. /**
  34320. * XR configuration.
  34321. * @typedef {Object} XRConfig
  34322. * @property {Boolean} enabled - Whether to globally enable XR or not.
  34323. */
  34324. /**
  34325. * The renderer's XR manager.
  34326. *
  34327. * @type {XRManager}
  34328. */
  34329. this.xr = new XRManager( this );
  34330. /**
  34331. * Debug configuration.
  34332. * @typedef {Object} DebugConfig
  34333. * @property {Boolean} checkShaderErrors - Whether shader errors should be checked or not.
  34334. * @property {Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  34335. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  34336. */
  34337. /**
  34338. * The renderer's debug configuration.
  34339. *
  34340. * @type {module:Renderer~DebugConfig}
  34341. */
  34342. this.debug = {
  34343. checkShaderErrors: true,
  34344. onShaderError: null,
  34345. getShaderAsync: async ( scene, camera, object ) => {
  34346. await this.compileAsync( scene, camera );
  34347. const renderList = this._renderLists.get( scene, camera );
  34348. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  34349. const material = scene.overrideMaterial || object.material;
  34350. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  34351. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  34352. return { fragmentShader, vertexShader };
  34353. }
  34354. };
  34355. }
  34356. /**
  34357. * Initializes the renderer so it is ready for usage.
  34358. *
  34359. * @async
  34360. * @return {Promise} A Promise that resolves when the renderer has been initialized.
  34361. */
  34362. async init() {
  34363. if ( this._initialized ) {
  34364. throw new Error( 'Renderer: Backend has already been initialized.' );
  34365. }
  34366. if ( this._initPromise !== null ) {
  34367. return this._initPromise;
  34368. }
  34369. this._initPromise = new Promise( async ( resolve, reject ) => {
  34370. let backend = this.backend;
  34371. try {
  34372. await backend.init( this );
  34373. } catch ( error ) {
  34374. if ( this._getFallback !== null ) {
  34375. // try the fallback
  34376. try {
  34377. this.backend = backend = this._getFallback( error );
  34378. await backend.init( this );
  34379. } catch ( error ) {
  34380. reject( error );
  34381. return;
  34382. }
  34383. } else {
  34384. reject( error );
  34385. return;
  34386. }
  34387. }
  34388. this._nodes = new Nodes( this, backend );
  34389. this._animation = new Animation( this._nodes, this.info );
  34390. this._attributes = new Attributes( backend );
  34391. this._background = new Background( this, this._nodes );
  34392. this._geometries = new Geometries( this._attributes, this.info );
  34393. this._textures = new Textures( this, backend, this.info );
  34394. this._pipelines = new Pipelines( backend, this._nodes );
  34395. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  34396. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  34397. this._renderLists = new RenderLists( this.lighting );
  34398. this._bundles = new RenderBundles();
  34399. this._renderContexts = new RenderContexts();
  34400. //
  34401. this._animation.start();
  34402. this._initialized = true;
  34403. resolve();
  34404. } );
  34405. return this._initPromise;
  34406. }
  34407. /**
  34408. * The coordinate system of the renderer. The value of this property
  34409. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  34410. * `THREE.WebGPUCoordinateSystem`.
  34411. *
  34412. * @readonly
  34413. * @type {Number}
  34414. */
  34415. get coordinateSystem() {
  34416. return this.backend.coordinateSystem;
  34417. }
  34418. /**
  34419. * Compiles all materials in the given scene. This can be useful to avoid a
  34420. * phenomenon which is called "shader compilation stutter", which occurs when
  34421. * rendering an object with a new shader for the first time.
  34422. *
  34423. * If you want to add a 3D object to an existing scene, use the third optional
  34424. * parameter for applying the target scene. Note that the (target) scene's lighting
  34425. * and environment must be configured before calling this method.
  34426. *
  34427. * @async
  34428. * @param {Object3D} scene - The scene or 3D object to precompile.
  34429. * @param {Camera} camera - The camera that is used to render the scene.
  34430. * @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.
  34431. * @return {Promise<Array>} A Promise that resolves when the compile has been finished.
  34432. */
  34433. async compileAsync( scene, camera, targetScene = null ) {
  34434. if ( this._isDeviceLost === true ) return;
  34435. if ( this._initialized === false ) await this.init();
  34436. // preserve render tree
  34437. const nodeFrame = this._nodes.nodeFrame;
  34438. const previousRenderId = nodeFrame.renderId;
  34439. const previousRenderContext = this._currentRenderContext;
  34440. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  34441. const previousCompilationPromises = this._compilationPromises;
  34442. //
  34443. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  34444. if ( targetScene === null ) targetScene = scene;
  34445. const renderTarget = this._renderTarget;
  34446. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  34447. const activeMipmapLevel = this._activeMipmapLevel;
  34448. const compilationPromises = [];
  34449. this._currentRenderContext = renderContext;
  34450. this._currentRenderObjectFunction = this.renderObject;
  34451. this._handleObjectFunction = this._createObjectPipeline;
  34452. this._compilationPromises = compilationPromises;
  34453. nodeFrame.renderId ++;
  34454. //
  34455. nodeFrame.update();
  34456. //
  34457. renderContext.depth = this.depth;
  34458. renderContext.stencil = this.stencil;
  34459. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  34460. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  34461. //
  34462. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  34463. //
  34464. const renderList = this._renderLists.get( scene, camera );
  34465. renderList.begin();
  34466. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  34467. // include lights from target scene
  34468. if ( targetScene !== scene ) {
  34469. targetScene.traverseVisible( function ( object ) {
  34470. if ( object.isLight && object.layers.test( camera.layers ) ) {
  34471. renderList.pushLight( object );
  34472. }
  34473. } );
  34474. }
  34475. renderList.finish();
  34476. //
  34477. if ( renderTarget !== null ) {
  34478. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  34479. const renderTargetData = this._textures.get( renderTarget );
  34480. renderContext.textures = renderTargetData.textures;
  34481. renderContext.depthTexture = renderTargetData.depthTexture;
  34482. } else {
  34483. renderContext.textures = null;
  34484. renderContext.depthTexture = null;
  34485. }
  34486. //
  34487. this._background.update( sceneRef, renderList, renderContext );
  34488. // process render lists
  34489. const opaqueObjects = renderList.opaque;
  34490. const transparentObjects = renderList.transparent;
  34491. const transparentDoublePassObjects = renderList.transparentDoublePass;
  34492. const lightsNode = renderList.lightsNode;
  34493. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34494. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  34495. // restore render tree
  34496. nodeFrame.renderId = previousRenderId;
  34497. this._currentRenderContext = previousRenderContext;
  34498. this._currentRenderObjectFunction = previousRenderObjectFunction;
  34499. this._compilationPromises = previousCompilationPromises;
  34500. this._handleObjectFunction = this._renderObjectDirect;
  34501. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  34502. await Promise.all( compilationPromises );
  34503. }
  34504. /**
  34505. * Renders the scene in an async fashion.
  34506. *
  34507. * @async
  34508. * @param {Object3D} scene - The scene or 3D object to render.
  34509. * @param {Camera} camera - The camera.
  34510. * @return {Promise} A Promise that resolves when the render has been finished.
  34511. */
  34512. async renderAsync( scene, camera ) {
  34513. if ( this._initialized === false ) await this.init();
  34514. const renderContext = this._renderScene( scene, camera );
  34515. await this.backend.resolveTimestampAsync( renderContext, 'render' );
  34516. }
  34517. /**
  34518. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  34519. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  34520. *
  34521. * @async
  34522. * @return {Promise} A Promise that resolves when synchronization has been finished.
  34523. */
  34524. async waitForGPU() {
  34525. await this.backend.waitForGPU();
  34526. }
  34527. /**
  34528. * Sets the given MRT configuration.
  34529. *
  34530. * @param {MRTNode} mrt - The MRT node to set.
  34531. * @return {Renderer} A reference to this renderer.
  34532. */
  34533. setMRT( mrt ) {
  34534. this._mrt = mrt;
  34535. return this;
  34536. }
  34537. /**
  34538. * Returns the MRT configuration.
  34539. *
  34540. * @return {MRTNode} The MRT configuration.
  34541. */
  34542. getMRT() {
  34543. return this._mrt;
  34544. }
  34545. /**
  34546. * Default implementation of the device lost callback.
  34547. *
  34548. * @private
  34549. * @param {Object} info - Information about the context lost.
  34550. */
  34551. _onDeviceLost( info ) {
  34552. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  34553. if ( info.reason ) {
  34554. errorMessage += `\nReason: ${info.reason}`;
  34555. }
  34556. console.error( errorMessage );
  34557. this._isDeviceLost = true;
  34558. }
  34559. /**
  34560. * Renders the given render bundle.
  34561. *
  34562. * @private
  34563. * @param {Object} bundle - Render bundle data.
  34564. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  34565. * @param {LightsNode} lightsNode - The current lights node.
  34566. */
  34567. _renderBundle( bundle, sceneRef, lightsNode ) {
  34568. const { bundleGroup, camera, renderList } = bundle;
  34569. const renderContext = this._currentRenderContext;
  34570. //
  34571. const renderBundle = this._bundles.get( bundleGroup, camera );
  34572. const renderBundleData = this.backend.get( renderBundle );
  34573. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  34574. //
  34575. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  34576. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  34577. renderBundleData.renderContexts.add( renderContext );
  34578. if ( renderBundleNeedsUpdate ) {
  34579. this.backend.beginBundle( renderContext );
  34580. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  34581. renderBundleData.renderObjects = [];
  34582. }
  34583. this._currentRenderBundle = renderBundle;
  34584. const opaqueObjects = renderList.opaque;
  34585. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34586. this._currentRenderBundle = null;
  34587. //
  34588. this.backend.finishBundle( renderContext, renderBundle );
  34589. renderBundleData.version = bundleGroup.version;
  34590. } else {
  34591. const { renderObjects } = renderBundleData;
  34592. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  34593. const renderObject = renderObjects[ i ];
  34594. if ( this._nodes.needsRefresh( renderObject ) ) {
  34595. this._nodes.updateBefore( renderObject );
  34596. this._nodes.updateForRender( renderObject );
  34597. this._bindings.updateForRender( renderObject );
  34598. this._nodes.updateAfter( renderObject );
  34599. }
  34600. }
  34601. }
  34602. this.backend.addBundle( renderContext, renderBundle );
  34603. }
  34604. /**
  34605. * Renders the scene or 3D object with the given camera. This method can only be called
  34606. * if the renderer has been initialized.
  34607. *
  34608. * The target of the method is the default framebuffer (meaning the canvas)
  34609. * or alternatively a render target when specified via `setRenderTarget()`.
  34610. *
  34611. * @param {Object3D} scene - The scene or 3D object to render.
  34612. * @param {Camera} camera - The camera to render the scene with.
  34613. * @return {Promise?} A Promise that resolve when the scene has been rendered.
  34614. * Only returned when the renderer has not been initialized.
  34615. */
  34616. render( scene, camera ) {
  34617. if ( this._initialized === false ) {
  34618. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  34619. return this.renderAsync( scene, camera );
  34620. }
  34621. this._renderScene( scene, camera );
  34622. }
  34623. /**
  34624. * Returns an internal render target which is used when computing the output tone mapping
  34625. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  34626. * pass and not inline to achieve more correct results.
  34627. *
  34628. * @private
  34629. * @return {RenderTarget?} The render target. The method returns `null` if no output conversion should be applied.
  34630. */
  34631. _getFrameBufferTarget() {
  34632. const { currentToneMapping, currentColorSpace } = this;
  34633. const useToneMapping = currentToneMapping !== NoToneMapping;
  34634. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  34635. if ( useToneMapping === false && useColorSpace === false ) return null;
  34636. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  34637. const { depth, stencil } = this;
  34638. let frameBufferTarget = this._frameBufferTarget;
  34639. if ( frameBufferTarget === null ) {
  34640. frameBufferTarget = new RenderTarget( width, height, {
  34641. depthBuffer: depth,
  34642. stencilBuffer: stencil,
  34643. type: HalfFloatType, // FloatType
  34644. format: RGBAFormat,
  34645. colorSpace: LinearSRGBColorSpace,
  34646. generateMipmaps: false,
  34647. minFilter: LinearFilter,
  34648. magFilter: LinearFilter,
  34649. samples: this.samples
  34650. } );
  34651. frameBufferTarget.isPostProcessingRenderTarget = true;
  34652. this._frameBufferTarget = frameBufferTarget;
  34653. }
  34654. frameBufferTarget.depthBuffer = depth;
  34655. frameBufferTarget.stencilBuffer = stencil;
  34656. frameBufferTarget.setSize( width, height );
  34657. frameBufferTarget.viewport.copy( this._viewport );
  34658. frameBufferTarget.scissor.copy( this._scissor );
  34659. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  34660. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  34661. frameBufferTarget.scissorTest = this._scissorTest;
  34662. return frameBufferTarget;
  34663. }
  34664. /**
  34665. * Renders the scene or 3D object with the given camera.
  34666. *
  34667. * @private
  34668. * @param {Object3D} scene - The scene or 3D object to render.
  34669. * @param {Camera} camera - The camera to render the scene with.
  34670. * @param {Boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  34671. * @return {RenderContext} The current render context.
  34672. */
  34673. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  34674. if ( this._isDeviceLost === true ) return;
  34675. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  34676. // preserve render tree
  34677. const nodeFrame = this._nodes.nodeFrame;
  34678. const previousRenderId = nodeFrame.renderId;
  34679. const previousRenderContext = this._currentRenderContext;
  34680. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  34681. //
  34682. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  34683. const outputRenderTarget = this._renderTarget;
  34684. const activeCubeFace = this._activeCubeFace;
  34685. const activeMipmapLevel = this._activeMipmapLevel;
  34686. //
  34687. let renderTarget;
  34688. if ( frameBufferTarget !== null ) {
  34689. renderTarget = frameBufferTarget;
  34690. this.setRenderTarget( renderTarget );
  34691. } else {
  34692. renderTarget = outputRenderTarget;
  34693. }
  34694. //
  34695. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  34696. this._currentRenderContext = renderContext;
  34697. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  34698. //
  34699. this.info.calls ++;
  34700. this.info.render.calls ++;
  34701. this.info.render.frameCalls ++;
  34702. nodeFrame.renderId = this.info.calls;
  34703. //
  34704. const coordinateSystem = this.coordinateSystem;
  34705. const xr = this.xr;
  34706. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  34707. camera.coordinateSystem = coordinateSystem;
  34708. camera.updateProjectionMatrix();
  34709. if ( camera.isArrayCamera ) {
  34710. for ( const subCamera of camera.cameras ) {
  34711. subCamera.coordinateSystem = coordinateSystem;
  34712. subCamera.updateProjectionMatrix();
  34713. }
  34714. }
  34715. }
  34716. //
  34717. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  34718. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  34719. if ( xr.enabled === true && xr.isPresenting === true ) {
  34720. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  34721. camera = xr.getCamera(); // use XR camera for rendering
  34722. }
  34723. //
  34724. let viewport = this._viewport;
  34725. let scissor = this._scissor;
  34726. let pixelRatio = this._pixelRatio;
  34727. if ( renderTarget !== null ) {
  34728. viewport = renderTarget.viewport;
  34729. scissor = renderTarget.scissor;
  34730. pixelRatio = 1;
  34731. }
  34732. this.getDrawingBufferSize( _drawingBufferSize );
  34733. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  34734. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  34735. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  34736. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  34737. renderContext.viewportValue.width >>= activeMipmapLevel;
  34738. renderContext.viewportValue.height >>= activeMipmapLevel;
  34739. renderContext.viewportValue.minDepth = minDepth;
  34740. renderContext.viewportValue.maxDepth = maxDepth;
  34741. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  34742. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  34743. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  34744. renderContext.scissorValue.width >>= activeMipmapLevel;
  34745. renderContext.scissorValue.height >>= activeMipmapLevel;
  34746. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  34747. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  34748. //
  34749. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  34750. //
  34751. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  34752. _frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  34753. const renderList = this._renderLists.get( scene, camera );
  34754. renderList.begin();
  34755. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  34756. renderList.finish();
  34757. if ( this.sortObjects === true ) {
  34758. renderList.sort( this._opaqueSort, this._transparentSort );
  34759. }
  34760. //
  34761. if ( renderTarget !== null ) {
  34762. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  34763. const renderTargetData = this._textures.get( renderTarget );
  34764. renderContext.textures = renderTargetData.textures;
  34765. renderContext.depthTexture = renderTargetData.depthTexture;
  34766. renderContext.width = renderTargetData.width;
  34767. renderContext.height = renderTargetData.height;
  34768. renderContext.renderTarget = renderTarget;
  34769. renderContext.depth = renderTarget.depthBuffer;
  34770. renderContext.stencil = renderTarget.stencilBuffer;
  34771. } else {
  34772. renderContext.textures = null;
  34773. renderContext.depthTexture = null;
  34774. renderContext.width = this.domElement.width;
  34775. renderContext.height = this.domElement.height;
  34776. renderContext.depth = this.depth;
  34777. renderContext.stencil = this.stencil;
  34778. }
  34779. renderContext.width >>= activeMipmapLevel;
  34780. renderContext.height >>= activeMipmapLevel;
  34781. renderContext.activeCubeFace = activeCubeFace;
  34782. renderContext.activeMipmapLevel = activeMipmapLevel;
  34783. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  34784. //
  34785. if ( xr.enabled === false || xr.isPresenting === false ) {
  34786. this._background.update( sceneRef, renderList, renderContext );
  34787. }
  34788. //
  34789. this.backend.beginRender( renderContext );
  34790. // process render lists
  34791. const {
  34792. bundles,
  34793. lightsNode,
  34794. transparentDoublePass: transparentDoublePassObjects,
  34795. transparent: transparentObjects,
  34796. opaque: opaqueObjects
  34797. } = renderList;
  34798. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  34799. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  34800. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  34801. // finish render pass
  34802. this.backend.finishRender( renderContext );
  34803. // restore render tree
  34804. nodeFrame.renderId = previousRenderId;
  34805. this._currentRenderContext = previousRenderContext;
  34806. this._currentRenderObjectFunction = previousRenderObjectFunction;
  34807. //
  34808. if ( frameBufferTarget !== null ) {
  34809. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  34810. const quad = this._quad;
  34811. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  34812. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  34813. quad.material.needsUpdate = true;
  34814. }
  34815. this._renderScene( quad, quad.camera, false );
  34816. }
  34817. //
  34818. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  34819. //
  34820. return renderContext;
  34821. }
  34822. /**
  34823. * Returns the maximum available anisotropy for texture filtering.
  34824. *
  34825. * @return {Number} The maximum available anisotropy.
  34826. */
  34827. getMaxAnisotropy() {
  34828. return this.backend.getMaxAnisotropy();
  34829. }
  34830. /**
  34831. * Returns the active cube face.
  34832. *
  34833. * @return {Number} The active cube face.
  34834. */
  34835. getActiveCubeFace() {
  34836. return this._activeCubeFace;
  34837. }
  34838. /**
  34839. * Returns the active mipmap level.
  34840. *
  34841. * @return {Number} The active mipmap level.
  34842. */
  34843. getActiveMipmapLevel() {
  34844. return this._activeMipmapLevel;
  34845. }
  34846. /**
  34847. * Applications are advised to always define the animation loop
  34848. * with this method and not manually with `requestAnimationFrame()`
  34849. * for best compatibility.
  34850. *
  34851. * @async
  34852. * @param {Function} callback - The application's animation loop.
  34853. * @return {Promise} A Promise that resolves when the set has been executed.
  34854. */
  34855. async setAnimationLoop( callback ) {
  34856. if ( this._initialized === false ) await this.init();
  34857. this._animation.setAnimationLoop( callback );
  34858. }
  34859. /**
  34860. * Can be used to transfer buffer data from a storage buffer attribute
  34861. * from the GPU to the CPU in context of compute shaders.
  34862. *
  34863. * @async
  34864. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  34865. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  34866. */
  34867. async getArrayBufferAsync( attribute ) {
  34868. return await this.backend.getArrayBufferAsync( attribute );
  34869. }
  34870. /**
  34871. * Returns the rendering context.
  34872. *
  34873. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  34874. */
  34875. getContext() {
  34876. return this.backend.getContext();
  34877. }
  34878. /**
  34879. * Returns the pixel ratio.
  34880. *
  34881. * @return {Number} The pixel ratio.
  34882. */
  34883. getPixelRatio() {
  34884. return this._pixelRatio;
  34885. }
  34886. /**
  34887. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  34888. *
  34889. * @param {Vector2} target - The method writes the result in this target object.
  34890. * @return {Vector2} The drawing buffer size.
  34891. */
  34892. getDrawingBufferSize( target ) {
  34893. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  34894. }
  34895. /**
  34896. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  34897. *
  34898. * @param {Vector2} target - The method writes the result in this target object.
  34899. * @return {Vector2} The drawing buffer size.
  34900. */
  34901. getSize( target ) {
  34902. return target.set( this._width, this._height );
  34903. }
  34904. /**
  34905. * Sets the given pixel ration and resizes the canvas if necessary.
  34906. *
  34907. * @param {Number} [value=1] - The pixel ratio.
  34908. */
  34909. setPixelRatio( value = 1 ) {
  34910. if ( this._pixelRatio === value ) return;
  34911. this._pixelRatio = value;
  34912. this.setSize( this._width, this._height, false );
  34913. }
  34914. /**
  34915. * This method allows to define the drawing buffer size by specifying
  34916. * width, height and pixel ratio all at once. The size of the drawing
  34917. * buffer is computed with this formula:
  34918. * ````
  34919. * size.x = width * pixelRatio;
  34920. * size.y = height * pixelRatio;
  34921. *```
  34922. *
  34923. * @param {Number} width - The width in logical pixels.
  34924. * @param {Number} height - The height in logical pixels.
  34925. * @param {Number} pixelRatio - The pixel ratio.
  34926. */
  34927. setDrawingBufferSize( width, height, pixelRatio ) {
  34928. this._width = width;
  34929. this._height = height;
  34930. this._pixelRatio = pixelRatio;
  34931. this.domElement.width = Math.floor( width * pixelRatio );
  34932. this.domElement.height = Math.floor( height * pixelRatio );
  34933. this.setViewport( 0, 0, width, height );
  34934. if ( this._initialized ) this.backend.updateSize();
  34935. }
  34936. /**
  34937. * Sets the size of the renderer.
  34938. *
  34939. * @param {Number} width - The width in logical pixels.
  34940. * @param {Number} height - The height in logical pixels.
  34941. * @param {Boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  34942. */
  34943. setSize( width, height, updateStyle = true ) {
  34944. this._width = width;
  34945. this._height = height;
  34946. this.domElement.width = Math.floor( width * this._pixelRatio );
  34947. this.domElement.height = Math.floor( height * this._pixelRatio );
  34948. if ( updateStyle === true ) {
  34949. this.domElement.style.width = width + 'px';
  34950. this.domElement.style.height = height + 'px';
  34951. }
  34952. this.setViewport( 0, 0, width, height );
  34953. if ( this._initialized ) this.backend.updateSize();
  34954. }
  34955. /**
  34956. * Defines a manual sort function for the opaque render list.
  34957. * Pass `null` to use the default sort.
  34958. *
  34959. * @param {Function} method - The sort function.
  34960. */
  34961. setOpaqueSort( method ) {
  34962. this._opaqueSort = method;
  34963. }
  34964. /**
  34965. * Defines a manual sort function for the transparent render list.
  34966. * Pass `null` to use the default sort.
  34967. *
  34968. * @param {Function} method - The sort function.
  34969. */
  34970. setTransparentSort( method ) {
  34971. this._transparentSort = method;
  34972. }
  34973. /**
  34974. * Returns the scissor rectangle.
  34975. *
  34976. * @param {Vector4} target - The method writes the result in this target object.
  34977. * @return {Vector4} The scissor rectangle.
  34978. */
  34979. getScissor( target ) {
  34980. const scissor = this._scissor;
  34981. target.x = scissor.x;
  34982. target.y = scissor.y;
  34983. target.width = scissor.width;
  34984. target.height = scissor.height;
  34985. return target;
  34986. }
  34987. /**
  34988. * Defines the scissor rectangle.
  34989. *
  34990. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  34991. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  34992. * @param {Number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  34993. * @param {Number} width - The width of the scissor box in logical pixel unit.
  34994. * @param {Number} height - The height of the scissor box in logical pixel unit.
  34995. */
  34996. setScissor( x, y, width, height ) {
  34997. const scissor = this._scissor;
  34998. if ( x.isVector4 ) {
  34999. scissor.copy( x );
  35000. } else {
  35001. scissor.set( x, y, width, height );
  35002. }
  35003. }
  35004. /**
  35005. * Returns the scissor test value.
  35006. *
  35007. * @return {Boolean} Whether the scissor test should be enabled or not.
  35008. */
  35009. getScissorTest() {
  35010. return this._scissorTest;
  35011. }
  35012. /**
  35013. * Defines the scissor test.
  35014. *
  35015. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  35016. */
  35017. setScissorTest( boolean ) {
  35018. this._scissorTest = boolean;
  35019. this.backend.setScissorTest( boolean );
  35020. }
  35021. /**
  35022. * Returns the viewport definition.
  35023. *
  35024. * @param {Vector4} target - The method writes the result in this target object.
  35025. * @return {Vector4} The viewport definition.
  35026. */
  35027. getViewport( target ) {
  35028. return target.copy( this._viewport );
  35029. }
  35030. /**
  35031. * Defines the viewport.
  35032. *
  35033. * @param {Number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35034. * @param {Number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  35035. * @param {Number} width - The width of the viewport in logical pixel unit.
  35036. * @param {Number} height - The height of the viewport in logical pixel unit.
  35037. * @param {Number} minDepth - The minimum depth value of the viewport. WebGPU only.
  35038. * @param {Number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  35039. */
  35040. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  35041. const viewport = this._viewport;
  35042. if ( x.isVector4 ) {
  35043. viewport.copy( x );
  35044. } else {
  35045. viewport.set( x, y, width, height );
  35046. }
  35047. viewport.minDepth = minDepth;
  35048. viewport.maxDepth = maxDepth;
  35049. }
  35050. /**
  35051. * Returns the clear color.
  35052. *
  35053. * @param {Color} target - The method writes the result in this target object.
  35054. * @return {Color} The clear color.
  35055. */
  35056. getClearColor( target ) {
  35057. return target.copy( this._clearColor );
  35058. }
  35059. /**
  35060. * Defines the clear color and optionally the clear alpha.
  35061. *
  35062. * @param {Color} color - The clear color.
  35063. * @param {Number} [alpha=1] - The clear alpha.
  35064. */
  35065. setClearColor( color, alpha = 1 ) {
  35066. this._clearColor.set( color );
  35067. this._clearColor.a = alpha;
  35068. }
  35069. /**
  35070. * Returns the clear alpha.
  35071. *
  35072. * @return {Number} The clear alpha.
  35073. */
  35074. getClearAlpha() {
  35075. return this._clearColor.a;
  35076. }
  35077. /**
  35078. * Defines the clear alpha.
  35079. *
  35080. * @param {Number} alpha - The clear alpha.
  35081. */
  35082. setClearAlpha( alpha ) {
  35083. this._clearColor.a = alpha;
  35084. }
  35085. /**
  35086. * Returns the clear depth.
  35087. *
  35088. * @return {Number} The clear depth.
  35089. */
  35090. getClearDepth() {
  35091. return this._clearDepth;
  35092. }
  35093. /**
  35094. * Defines the clear depth.
  35095. *
  35096. * @param {Number} depth - The clear depth.
  35097. */
  35098. setClearDepth( depth ) {
  35099. this._clearDepth = depth;
  35100. }
  35101. /**
  35102. * Returns the clear stencil.
  35103. *
  35104. * @return {Number} The clear stencil.
  35105. */
  35106. getClearStencil() {
  35107. return this._clearStencil;
  35108. }
  35109. /**
  35110. * Defines the clear stencil.
  35111. *
  35112. * @param {Number} stencil - The clear stencil.
  35113. */
  35114. setClearStencil( stencil ) {
  35115. this._clearStencil = stencil;
  35116. }
  35117. /**
  35118. * This method performs an occlusion query for the given 3D object.
  35119. * It returns `true` if the given 3D object is fully occluded by other
  35120. * 3D objects in the scene.
  35121. *
  35122. * @param {Object3D} object - The 3D object to test.
  35123. * @return {Boolean} Whether the 3D object is fully occluded or not.
  35124. */
  35125. isOccluded( object ) {
  35126. const renderContext = this._currentRenderContext;
  35127. return renderContext && this.backend.isOccluded( renderContext, object );
  35128. }
  35129. /**
  35130. * Performs a manual clear operation. This method ignores `autoClear` properties.
  35131. *
  35132. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35133. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35134. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35135. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35136. * Only returned when the renderer has not been initialized.
  35137. */
  35138. clear( color = true, depth = true, stencil = true ) {
  35139. if ( this._initialized === false ) {
  35140. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  35141. return this.clearAsync( color, depth, stencil );
  35142. }
  35143. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35144. let renderContext = null;
  35145. if ( renderTarget !== null ) {
  35146. this._textures.updateRenderTarget( renderTarget );
  35147. const renderTargetData = this._textures.get( renderTarget );
  35148. renderContext = this._renderContexts.getForClear( renderTarget );
  35149. renderContext.textures = renderTargetData.textures;
  35150. renderContext.depthTexture = renderTargetData.depthTexture;
  35151. renderContext.width = renderTargetData.width;
  35152. renderContext.height = renderTargetData.height;
  35153. renderContext.renderTarget = renderTarget;
  35154. renderContext.depth = renderTarget.depthBuffer;
  35155. renderContext.stencil = renderTarget.stencilBuffer;
  35156. }
  35157. // #30329
  35158. renderContext.clearColorValue = this._clearColor;
  35159. this.backend.clear( color, depth, stencil, renderContext );
  35160. if ( renderTarget !== null && this._renderTarget === null ) {
  35161. // If a color space transform or tone mapping is required,
  35162. // the clear operation clears the intermediate renderTarget texture, but does not update the screen canvas.
  35163. const quad = this._quad;
  35164. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  35165. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  35166. quad.material.needsUpdate = true;
  35167. }
  35168. this._renderScene( quad, quad.camera, false );
  35169. }
  35170. }
  35171. /**
  35172. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  35173. *
  35174. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35175. * Only returned when the renderer has not been initialized.
  35176. */
  35177. clearColor() {
  35178. return this.clear( true, false, false );
  35179. }
  35180. /**
  35181. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  35182. *
  35183. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35184. * Only returned when the renderer has not been initialized.
  35185. */
  35186. clearDepth() {
  35187. return this.clear( false, true, false );
  35188. }
  35189. /**
  35190. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  35191. *
  35192. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35193. * Only returned when the renderer has not been initialized.
  35194. */
  35195. clearStencil() {
  35196. return this.clear( false, false, true );
  35197. }
  35198. /**
  35199. * Async version of {@link module:Renderer~Renderer#clear}.
  35200. *
  35201. * @async
  35202. * @param {Boolean} [color=true] - Whether the color buffer should be cleared or not.
  35203. * @param {Boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  35204. * @param {Boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  35205. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35206. */
  35207. async clearAsync( color = true, depth = true, stencil = true ) {
  35208. if ( this._initialized === false ) await this.init();
  35209. this.clear( color, depth, stencil );
  35210. }
  35211. /**
  35212. * Async version of {@link module:Renderer~Renderer#clearColor}.
  35213. *
  35214. * @async
  35215. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35216. */
  35217. async clearColorAsync() {
  35218. this.clearAsync( true, false, false );
  35219. }
  35220. /**
  35221. * Async version of {@link module:Renderer~Renderer#clearDepth}.
  35222. *
  35223. * @async
  35224. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35225. */
  35226. async clearDepthAsync() {
  35227. this.clearAsync( false, true, false );
  35228. }
  35229. /**
  35230. * Async version of {@link module:Renderer~Renderer#clearStencil}.
  35231. *
  35232. * @async
  35233. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  35234. */
  35235. async clearStencilAsync() {
  35236. this.clearAsync( false, false, true );
  35237. }
  35238. /**
  35239. * The current output tone mapping of the renderer. When a render target is set,
  35240. * the output tone mapping is always `NoToneMapping`.
  35241. *
  35242. * @type {Number}
  35243. */
  35244. get currentToneMapping() {
  35245. return this._renderTarget !== null ? NoToneMapping : this.toneMapping;
  35246. }
  35247. /**
  35248. * The current output color space of the renderer. When a render target is set,
  35249. * the output color space is always `LinearSRGBColorSpace`.
  35250. *
  35251. * @type {String}
  35252. */
  35253. get currentColorSpace() {
  35254. return this._renderTarget !== null ? LinearSRGBColorSpace : this.outputColorSpace;
  35255. }
  35256. /**
  35257. * Frees all internal resources of the renderer. Call this method if the renderer
  35258. * is no longer in use by your app.
  35259. */
  35260. dispose() {
  35261. this.info.dispose();
  35262. this.backend.dispose();
  35263. this._animation.dispose();
  35264. this._objects.dispose();
  35265. this._pipelines.dispose();
  35266. this._nodes.dispose();
  35267. this._bindings.dispose();
  35268. this._renderLists.dispose();
  35269. this._renderContexts.dispose();
  35270. this._textures.dispose();
  35271. this.setRenderTarget( null );
  35272. this.setAnimationLoop( null );
  35273. }
  35274. /**
  35275. * Ensures the renderer is XR compatible.
  35276. *
  35277. * @async
  35278. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  35279. */
  35280. async makeXRCompatible() {
  35281. await this.backend.makeXRCompatible();
  35282. }
  35283. /**
  35284. * Sets the XR rendering destination.
  35285. *
  35286. * @param {WebGLFramebuffer} xrTarget - The XR target.
  35287. */
  35288. setXRTarget( xrTarget ) {
  35289. this.backend.setXRTarget( xrTarget );
  35290. }
  35291. /**
  35292. * Sets the given render target. Calling this method means the renderer does not
  35293. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  35294. * Use `null` as the first argument to reset the state.
  35295. *
  35296. * @param {RenderTarget?} renderTarget - The render target to set.
  35297. * @param {Number} [activeCubeFace=0] - The active cube face.
  35298. * @param {Number} [activeMipmapLevel=0] - The active mipmap level.
  35299. */
  35300. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  35301. this._renderTarget = renderTarget;
  35302. this._activeCubeFace = activeCubeFace;
  35303. this._activeMipmapLevel = activeMipmapLevel;
  35304. }
  35305. /**
  35306. * Returns the current render target.
  35307. *
  35308. * @return {RenderTarget?} The render target. Returns `null` if no render target is set.
  35309. */
  35310. getRenderTarget() {
  35311. return this._renderTarget;
  35312. }
  35313. /**
  35314. * Callback for {@link module:Renderer~Renderer#setRenderObjectFunction}.
  35315. *
  35316. * @callback renderObjectFunction
  35317. * @param {Object3D} object - The 3D object.
  35318. * @param {Scene} scene - The scene the 3D object belongs to.
  35319. * @param {Camera} camera - The camera the object should be rendered with.
  35320. * @param {BufferGeometry} geometry - The object's geometry.
  35321. * @param {Material} material - The object's material.
  35322. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35323. * @param {LightsNode} lightsNode - The current lights node.
  35324. * @param {ClippingContext} clippingContext - The clipping context.
  35325. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35326. */
  35327. /**
  35328. * Sets the given render object function. Calling this method overwrites the default implementation
  35329. * which is {@link module:Renderer~Renderer#renderObject}. Defining a custom function can be useful
  35330. * if you want to modify the way objects are rendered. For example you can define things like "every
  35331. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  35332. * The custom function must always call `renderObject()` in its implementation.
  35333. *
  35334. * Use `null` as the first argument to reset the state.
  35335. *
  35336. * @param {module:Renderer~renderObjectFunction?} renderObjectFunction - The render object function.
  35337. */
  35338. setRenderObjectFunction( renderObjectFunction ) {
  35339. this._renderObjectFunction = renderObjectFunction;
  35340. }
  35341. /**
  35342. * Returns the current render object function.
  35343. *
  35344. * @return {Function?} The current render object function. Returns `null` if no function is set.
  35345. */
  35346. getRenderObjectFunction() {
  35347. return this._renderObjectFunction;
  35348. }
  35349. /**
  35350. * Execute a single or an array of compute nodes. This method can only be called
  35351. * if the renderer has been initialized.
  35352. *
  35353. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35354. * @return {Promise?} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  35355. */
  35356. compute( computeNodes ) {
  35357. if ( this._isDeviceLost === true ) return;
  35358. if ( this._initialized === false ) {
  35359. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  35360. return this.computeAsync( computeNodes );
  35361. }
  35362. //
  35363. const nodeFrame = this._nodes.nodeFrame;
  35364. const previousRenderId = nodeFrame.renderId;
  35365. //
  35366. this.info.calls ++;
  35367. this.info.compute.calls ++;
  35368. this.info.compute.frameCalls ++;
  35369. nodeFrame.renderId = this.info.calls;
  35370. //
  35371. const backend = this.backend;
  35372. const pipelines = this._pipelines;
  35373. const bindings = this._bindings;
  35374. const nodes = this._nodes;
  35375. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  35376. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  35377. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  35378. }
  35379. backend.beginCompute( computeNodes );
  35380. for ( const computeNode of computeList ) {
  35381. // onInit
  35382. if ( pipelines.has( computeNode ) === false ) {
  35383. const dispose = () => {
  35384. computeNode.removeEventListener( 'dispose', dispose );
  35385. pipelines.delete( computeNode );
  35386. bindings.delete( computeNode );
  35387. nodes.delete( computeNode );
  35388. };
  35389. computeNode.addEventListener( 'dispose', dispose );
  35390. //
  35391. const onInitFn = computeNode.onInitFunction;
  35392. if ( onInitFn !== null ) {
  35393. onInitFn.call( computeNode, { renderer: this } );
  35394. }
  35395. }
  35396. nodes.updateForCompute( computeNode );
  35397. bindings.updateForCompute( computeNode );
  35398. const computeBindings = bindings.getForCompute( computeNode );
  35399. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  35400. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  35401. }
  35402. backend.finishCompute( computeNodes );
  35403. //
  35404. nodeFrame.renderId = previousRenderId;
  35405. }
  35406. /**
  35407. * Execute a single or an array of compute nodes.
  35408. *
  35409. * @async
  35410. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  35411. * @return {Promise} A Promise that resolve when the compute has finished.
  35412. */
  35413. async computeAsync( computeNodes ) {
  35414. if ( this._initialized === false ) await this.init();
  35415. this.compute( computeNodes );
  35416. await this.backend.resolveTimestampAsync( computeNodes, 'compute' );
  35417. }
  35418. /**
  35419. * Checks if the given feature is supported by the selected backend.
  35420. *
  35421. * @async
  35422. * @param {String} name - The feature's name.
  35423. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  35424. */
  35425. async hasFeatureAsync( name ) {
  35426. if ( this._initialized === false ) await this.init();
  35427. return this.backend.hasFeature( name );
  35428. }
  35429. /**
  35430. * Checks if the given feature is supported by the selected backend. If the
  35431. * renderer has not been initialized, this method always returns `false`.
  35432. *
  35433. * @param {String} name - The feature's name.
  35434. * @return {Boolean} Whether the feature is supported or not.
  35435. */
  35436. hasFeature( name ) {
  35437. if ( this._initialized === false ) {
  35438. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  35439. return false;
  35440. }
  35441. return this.backend.hasFeature( name );
  35442. }
  35443. /**
  35444. * Returns `true` when the renderer has been initialized.
  35445. *
  35446. * @return {Boolean} Whether the renderer has been initialized or not.
  35447. */
  35448. hasInitialized() {
  35449. return this._initialized;
  35450. }
  35451. /**
  35452. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35453. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35454. *
  35455. * @async
  35456. * @param {Texture} texture - The texture.
  35457. * @return {Promise} A Promise that resolves when the texture has been initialized.
  35458. */
  35459. async initTextureAsync( texture ) {
  35460. if ( this._initialized === false ) await this.init();
  35461. this._textures.updateTexture( texture );
  35462. }
  35463. /**
  35464. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  35465. * (which can cause noticeable lags due to decode and GPU upload overhead).
  35466. *
  35467. * This method can only be used if the renderer has been initialized.
  35468. *
  35469. * @param {Texture} texture - The texture.
  35470. */
  35471. initTexture( texture ) {
  35472. if ( this._initialized === false ) {
  35473. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  35474. }
  35475. this._textures.updateTexture( texture );
  35476. }
  35477. /**
  35478. * Copies the current bound framebuffer into the given texture.
  35479. *
  35480. * @param {FramebufferTexture} framebufferTexture - The texture.
  35481. * @param {Vector2|Vector4} rectangle - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  35482. */
  35483. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  35484. if ( rectangle !== null ) {
  35485. if ( rectangle.isVector2 ) {
  35486. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  35487. } else if ( rectangle.isVector4 ) {
  35488. rectangle = _vector4.copy( rectangle ).floor();
  35489. } else {
  35490. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  35491. return;
  35492. }
  35493. } else {
  35494. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  35495. }
  35496. //
  35497. let renderContext = this._currentRenderContext;
  35498. let renderTarget;
  35499. if ( renderContext !== null ) {
  35500. renderTarget = renderContext.renderTarget;
  35501. } else {
  35502. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  35503. if ( renderTarget !== null ) {
  35504. this._textures.updateRenderTarget( renderTarget );
  35505. renderContext = this._textures.get( renderTarget );
  35506. }
  35507. }
  35508. //
  35509. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  35510. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  35511. }
  35512. /**
  35513. * Copies data of source texture into a destination texture.
  35514. *
  35515. * @param {Texture} srcTexture - The source texture.
  35516. * @param {Texture} dstTexture - The destination texture.
  35517. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  35518. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  35519. * @param {Number} level - The mipmap level to copy.
  35520. */
  35521. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  35522. this._textures.updateTexture( srcTexture );
  35523. this._textures.updateTexture( dstTexture );
  35524. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  35525. }
  35526. /**
  35527. * Reads pixel data from the given render target.
  35528. *
  35529. * @async
  35530. * @param {RenderTarget} renderTarget - The render target to read from.
  35531. * @param {Number} x - The `x` coordinate of the copy region's origin.
  35532. * @param {Number} y - The `y` coordinate of the copy region's origin.
  35533. * @param {Number} width - The width of the copy region.
  35534. * @param {Number} height - The height of the copy region.
  35535. * @param {Number} [textureIndex=0] - The texture index of a MRT render target.
  35536. * @param {Number} [faceIndex=0] - The active cube face index.
  35537. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  35538. */
  35539. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  35540. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  35541. }
  35542. /**
  35543. * Analyzes the given 3D object's hierarchy and builds render lists from the
  35544. * processed hierarchy.
  35545. *
  35546. * @param {Object3D} object - The 3D object to process (usually a scene).
  35547. * @param {Camera} camera - The camera the object is rendered with.
  35548. * @param {Number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  35549. * @param {RenderList} renderList - The current render list.
  35550. * @param {ClippingContext} clippingContext - The current clipping context.
  35551. */
  35552. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  35553. if ( object.visible === false ) return;
  35554. const visible = object.layers.test( camera.layers );
  35555. if ( visible ) {
  35556. if ( object.isGroup ) {
  35557. groupOrder = object.renderOrder;
  35558. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  35559. } else if ( object.isLOD ) {
  35560. if ( object.autoUpdate === true ) object.update( camera );
  35561. } else if ( object.isLight ) {
  35562. renderList.pushLight( object );
  35563. } else if ( object.isSprite ) {
  35564. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  35565. if ( this.sortObjects === true ) {
  35566. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  35567. }
  35568. const { geometry, material } = object;
  35569. if ( material.visible ) {
  35570. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35571. }
  35572. }
  35573. } else if ( object.isLineLoop ) {
  35574. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  35575. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  35576. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  35577. const { geometry, material } = object;
  35578. if ( this.sortObjects === true ) {
  35579. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  35580. _vector4
  35581. .copy( geometry.boundingSphere.center )
  35582. .applyMatrix4( object.matrixWorld )
  35583. .applyMatrix4( _projScreenMatrix );
  35584. }
  35585. if ( Array.isArray( material ) ) {
  35586. const groups = geometry.groups;
  35587. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  35588. const group = groups[ i ];
  35589. const groupMaterial = material[ group.materialIndex ];
  35590. if ( groupMaterial && groupMaterial.visible ) {
  35591. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  35592. }
  35593. }
  35594. } else if ( material.visible ) {
  35595. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  35596. }
  35597. }
  35598. }
  35599. }
  35600. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  35601. const baseRenderList = renderList;
  35602. // replace render list
  35603. renderList = this._renderLists.get( object, camera );
  35604. renderList.begin();
  35605. baseRenderList.pushBundle( {
  35606. bundleGroup: object,
  35607. camera,
  35608. renderList,
  35609. } );
  35610. renderList.finish();
  35611. }
  35612. const children = object.children;
  35613. for ( let i = 0, l = children.length; i < l; i ++ ) {
  35614. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  35615. }
  35616. }
  35617. /**
  35618. * Renders the given render bundles.
  35619. *
  35620. * @private
  35621. * @param {Array<Object>} bundles - Array with render bundle data.
  35622. * @param {Scene} sceneRef - The scene the render bundles belong to.
  35623. * @param {LightsNode} lightsNode - The current lights node.
  35624. */
  35625. _renderBundles( bundles, sceneRef, lightsNode ) {
  35626. for ( const bundle of bundles ) {
  35627. this._renderBundle( bundle, sceneRef, lightsNode );
  35628. }
  35629. }
  35630. /**
  35631. * Renders the transparent objects from the given render lists.
  35632. *
  35633. * @private
  35634. * @param {Array<Object>} renderList - The transparent render list.
  35635. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  35636. * @param {Camera} camera - The camera the render list should be rendered with.
  35637. * @param {Scene} scene - The scene the render list belongs to.
  35638. * @param {LightsNode} lightsNode - The current lights node.
  35639. */
  35640. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  35641. if ( doublePassList.length > 0 ) {
  35642. // render back side
  35643. for ( const { material } of doublePassList ) {
  35644. material.side = BackSide;
  35645. }
  35646. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  35647. // render front side
  35648. for ( const { material } of doublePassList ) {
  35649. material.side = FrontSide;
  35650. }
  35651. this._renderObjects( renderList, camera, scene, lightsNode );
  35652. // restore
  35653. for ( const { material } of doublePassList ) {
  35654. material.side = DoubleSide;
  35655. }
  35656. } else {
  35657. this._renderObjects( renderList, camera, scene, lightsNode );
  35658. }
  35659. }
  35660. /**
  35661. * Renders the objects from the given render list.
  35662. *
  35663. * @private
  35664. * @param {Array<Object>} renderList - The render list.
  35665. * @param {Camera} camera - The camera the render list should be rendered with.
  35666. * @param {Scene} scene - The scene the render list belongs to.
  35667. * @param {LightsNode} lightsNode - The current lights node.
  35668. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35669. */
  35670. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  35671. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  35672. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  35673. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  35674. }
  35675. }
  35676. /**
  35677. * This method represents the default render object function that manages the render lifecycle
  35678. * of the object.
  35679. *
  35680. * @param {Object3D} object - The 3D object.
  35681. * @param {Scene} scene - The scene the 3D object belongs to.
  35682. * @param {Camera} camera - The camera the object should be rendered with.
  35683. * @param {BufferGeometry} geometry - The object's geometry.
  35684. * @param {Material} material - The object's material.
  35685. * @param {Object?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35686. * @param {LightsNode} lightsNode - The current lights node.
  35687. * @param {ClippingContext} clippingContext - The clipping context.
  35688. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35689. */
  35690. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  35691. let overridePositionNode;
  35692. let overrideColorNode;
  35693. let overrideDepthNode;
  35694. //
  35695. object.onBeforeRender( this, scene, camera, geometry, material, group );
  35696. //
  35697. if ( scene.overrideMaterial !== null ) {
  35698. const overrideMaterial = scene.overrideMaterial;
  35699. if ( material.positionNode && material.positionNode.isNode ) {
  35700. overridePositionNode = overrideMaterial.positionNode;
  35701. overrideMaterial.positionNode = material.positionNode;
  35702. }
  35703. overrideMaterial.alphaTest = material.alphaTest;
  35704. overrideMaterial.alphaMap = material.alphaMap;
  35705. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  35706. if ( overrideMaterial.isShadowPassMaterial ) {
  35707. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  35708. if ( material.depthNode && material.depthNode.isNode ) {
  35709. overrideDepthNode = overrideMaterial.depthNode;
  35710. overrideMaterial.depthNode = material.depthNode;
  35711. }
  35712. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  35713. overrideColorNode = overrideMaterial.colorNode;
  35714. overrideMaterial.colorNode = material.castShadowNode;
  35715. }
  35716. }
  35717. material = overrideMaterial;
  35718. }
  35719. //
  35720. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  35721. material.side = BackSide;
  35722. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  35723. material.side = FrontSide;
  35724. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  35725. material.side = DoubleSide;
  35726. } else {
  35727. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  35728. }
  35729. //
  35730. if ( overridePositionNode !== undefined ) {
  35731. scene.overrideMaterial.positionNode = overridePositionNode;
  35732. }
  35733. if ( overrideDepthNode !== undefined ) {
  35734. scene.overrideMaterial.depthNode = overrideDepthNode;
  35735. }
  35736. if ( overrideColorNode !== undefined ) {
  35737. scene.overrideMaterial.colorNode = overrideColorNode;
  35738. }
  35739. //
  35740. object.onAfterRender( this, scene, camera, geometry, material, group );
  35741. }
  35742. /**
  35743. * This method represents the default `_handleObjectFunction` implementation which creates
  35744. * a render object from the given data and performs the draw command with the selected backend.
  35745. *
  35746. * @private
  35747. * @param {Object3D} object - The 3D object.
  35748. * @param {Material} material - The object's material.
  35749. * @param {Scene} scene - The scene the 3D object belongs to.
  35750. * @param {Camera} camera - The camera the object should be rendered with.
  35751. * @param {LightsNode} lightsNode - The current lights node.
  35752. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35753. * @param {ClippingContext} clippingContext - The clipping context.
  35754. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35755. */
  35756. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  35757. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  35758. renderObject.drawRange = object.geometry.drawRange;
  35759. renderObject.group = group;
  35760. //
  35761. const needsRefresh = this._nodes.needsRefresh( renderObject );
  35762. if ( needsRefresh ) {
  35763. this._nodes.updateBefore( renderObject );
  35764. this._geometries.updateForRender( renderObject );
  35765. this._nodes.updateForRender( renderObject );
  35766. this._bindings.updateForRender( renderObject );
  35767. }
  35768. this._pipelines.updateForRender( renderObject );
  35769. //
  35770. if ( this._currentRenderBundle !== null ) {
  35771. const renderBundleData = this.backend.get( this._currentRenderBundle );
  35772. renderBundleData.renderObjects.push( renderObject );
  35773. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  35774. }
  35775. this.backend.draw( renderObject, this.info );
  35776. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  35777. }
  35778. /**
  35779. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  35780. * Used in `compileAsync()`.
  35781. *
  35782. * @private
  35783. * @param {Object3D} object - The 3D object.
  35784. * @param {Material} material - The object's material.
  35785. * @param {Scene} scene - The scene the 3D object belongs to.
  35786. * @param {Camera} camera - The camera the object should be rendered with.
  35787. * @param {LightsNode} lightsNode - The current lights node.
  35788. * @param {{start: Number, count: Number}?} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  35789. * @param {ClippingContext} clippingContext - The clipping context.
  35790. * @param {String?} [passId=null] - An optional ID for identifying the pass.
  35791. */
  35792. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  35793. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  35794. renderObject.drawRange = object.geometry.drawRange;
  35795. renderObject.group = group;
  35796. //
  35797. this._nodes.updateBefore( renderObject );
  35798. this._geometries.updateForRender( renderObject );
  35799. this._nodes.updateForRender( renderObject );
  35800. this._bindings.updateForRender( renderObject );
  35801. this._pipelines.getForRender( renderObject, this._compilationPromises );
  35802. this._nodes.updateAfter( renderObject );
  35803. }
  35804. /**
  35805. * Alias for `compileAsync()`.
  35806. *
  35807. * @method
  35808. * @param {Object3D} scene - The scene or 3D object to precompile.
  35809. * @param {Camera} camera - The camera that is used to render the scene.
  35810. * @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.
  35811. * @return {Promise} A Promise that resolves when the compile has been finished.
  35812. */
  35813. get compile() {
  35814. return this.compileAsync;
  35815. }
  35816. }
  35817. /**
  35818. * A binding represents the connection between a resource (like a texture, sampler
  35819. * or uniform buffer) and the resource definition in a shader stage.
  35820. *
  35821. * This module is an abstract base class for all concrete bindings types.
  35822. *
  35823. * @abstract
  35824. * @private
  35825. */
  35826. class Binding {
  35827. /**
  35828. * Constructs a new binding.
  35829. *
  35830. * @param {String} [name=''] - The binding's name.
  35831. */
  35832. constructor( name = '' ) {
  35833. /**
  35834. * The binding's name.
  35835. *
  35836. * @type {String}
  35837. */
  35838. this.name = name;
  35839. /**
  35840. * A bitmask that defines in what shader stages the
  35841. * binding's resource is accessible.
  35842. *
  35843. * @type {Number}
  35844. */
  35845. this.visibility = 0;
  35846. }
  35847. /**
  35848. * Makes sure binding's resource is visible for the given shader stage.
  35849. *
  35850. * @param {Number} visibility - The shader stage.
  35851. */
  35852. setVisibility( visibility ) {
  35853. this.visibility |= visibility;
  35854. }
  35855. /**
  35856. * Clones the binding.
  35857. *
  35858. * @return {Binding} The cloned binding.
  35859. */
  35860. clone() {
  35861. return Object.assign( new this.constructor(), this );
  35862. }
  35863. }
  35864. /** @module BufferUtils **/
  35865. /**
  35866. * This function is usually called with the length in bytes of an array buffer.
  35867. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  35868. *
  35869. * @function
  35870. * @param {Number} floatLength - The buffer length.
  35871. * @return {Number} The padded length.
  35872. */
  35873. function getFloatLength( floatLength ) {
  35874. // ensure chunk size alignment (STD140 layout)
  35875. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  35876. }
  35877. /**
  35878. * Represents a buffer binding type.
  35879. *
  35880. * @private
  35881. * @abstract
  35882. * @augments Binding
  35883. */
  35884. class Buffer extends Binding {
  35885. /**
  35886. * Constructs a new buffer.
  35887. *
  35888. * @param {String} name - The buffer's name.
  35889. * @param {TypedArray} [buffer=null] - The buffer.
  35890. */
  35891. constructor( name, buffer = null ) {
  35892. super( name );
  35893. /**
  35894. * This flag can be used for type testing.
  35895. *
  35896. * @type {Boolean}
  35897. * @readonly
  35898. * @default true
  35899. */
  35900. this.isBuffer = true;
  35901. /**
  35902. * The bytes per element.
  35903. *
  35904. * @type {Number}
  35905. */
  35906. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  35907. /**
  35908. * A reference to the internal buffer.
  35909. *
  35910. * @private
  35911. * @type {TypedArray}
  35912. */
  35913. this._buffer = buffer;
  35914. }
  35915. /**
  35916. * The buffer's byte length.
  35917. *
  35918. * @type {Number}
  35919. * @readonly
  35920. */
  35921. get byteLength() {
  35922. return getFloatLength( this._buffer.byteLength );
  35923. }
  35924. /**
  35925. * A reference to the internal buffer.
  35926. *
  35927. * @type {Float32Array}
  35928. * @readonly
  35929. */
  35930. get buffer() {
  35931. return this._buffer;
  35932. }
  35933. /**
  35934. * Updates the binding.
  35935. *
  35936. * @return {Boolean} Whether the buffer has been updated and must be
  35937. * uploaded to the GPU.
  35938. */
  35939. update() {
  35940. return true;
  35941. }
  35942. }
  35943. /**
  35944. * Represents a uniform buffer binding type.
  35945. *
  35946. * @private
  35947. * @augments Buffer
  35948. */
  35949. class UniformBuffer extends Buffer {
  35950. /**
  35951. * Constructs a new uniform buffer.
  35952. *
  35953. * @param {String} name - The buffer's name.
  35954. * @param {TypedArray} [buffer=null] - The buffer.
  35955. */
  35956. constructor( name, buffer = null ) {
  35957. super( name, buffer );
  35958. /**
  35959. * This flag can be used for type testing.
  35960. *
  35961. * @type {Boolean}
  35962. * @readonly
  35963. * @default true
  35964. */
  35965. this.isUniformBuffer = true;
  35966. }
  35967. }
  35968. let _id$4 = 0;
  35969. /**
  35970. * A special form of uniform buffer binding type.
  35971. * It's buffer value is managed by a node object.
  35972. *
  35973. * @private
  35974. * @augments UniformBuffer
  35975. */
  35976. class NodeUniformBuffer extends UniformBuffer {
  35977. /**
  35978. * Constructs a new node-based uniform buffer.
  35979. *
  35980. * @param {BufferNode} nodeUniform - The uniform buffer node.
  35981. * @param {UniformGroupNode} groupNode - The uniform group node.
  35982. */
  35983. constructor( nodeUniform, groupNode ) {
  35984. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  35985. /**
  35986. * The uniform buffer node.
  35987. *
  35988. * @type {BufferNode}
  35989. */
  35990. this.nodeUniform = nodeUniform;
  35991. /**
  35992. * The uniform group node.
  35993. *
  35994. * @type {UniformGroupNode}
  35995. */
  35996. this.groupNode = groupNode;
  35997. }
  35998. /**
  35999. * The uniform buffer.
  36000. *
  36001. * @type {Float32Array}
  36002. */
  36003. get buffer() {
  36004. return this.nodeUniform.value;
  36005. }
  36006. }
  36007. /**
  36008. * This class represents a uniform buffer binding but with
  36009. * an API that allows to maintain individual uniform objects.
  36010. *
  36011. * @private
  36012. * @augments UniformBuffer
  36013. */
  36014. class UniformsGroup extends UniformBuffer {
  36015. /**
  36016. * Constructs a new uniforms group.
  36017. *
  36018. * @param {String} name - The group's name.
  36019. */
  36020. constructor( name ) {
  36021. super( name );
  36022. /**
  36023. * This flag can be used for type testing.
  36024. *
  36025. * @type {Boolean}
  36026. * @readonly
  36027. * @default true
  36028. */
  36029. this.isUniformsGroup = true;
  36030. /**
  36031. * An array with the raw uniform values.
  36032. *
  36033. * @private
  36034. * @type {Array<Number>?}
  36035. * @default null
  36036. */
  36037. this._values = null;
  36038. /**
  36039. * An array of uniform objects.
  36040. *
  36041. * The order of uniforms in this array must match the order of uniforms in the shader.
  36042. *
  36043. * @type {Array<Uniform>}
  36044. */
  36045. this.uniforms = [];
  36046. }
  36047. /**
  36048. * Adds a uniform to this group.
  36049. *
  36050. * @param {Uniform} uniform - The uniform to add.
  36051. * @return {UniformsGroup} A reference to this group.
  36052. */
  36053. addUniform( uniform ) {
  36054. this.uniforms.push( uniform );
  36055. return this;
  36056. }
  36057. /**
  36058. * Removes a uniform from this group.
  36059. *
  36060. * @param {Uniform} uniform - The uniform to remove.
  36061. * @return {UniformsGroup} A reference to this group.
  36062. */
  36063. removeUniform( uniform ) {
  36064. const index = this.uniforms.indexOf( uniform );
  36065. if ( index !== - 1 ) {
  36066. this.uniforms.splice( index, 1 );
  36067. }
  36068. return this;
  36069. }
  36070. /**
  36071. * An array with the raw uniform values.
  36072. *
  36073. * @type {Array<Number>}
  36074. */
  36075. get values() {
  36076. if ( this._values === null ) {
  36077. this._values = Array.from( this.buffer );
  36078. }
  36079. return this._values;
  36080. }
  36081. /**
  36082. * A Float32 array buffer with the uniform values.
  36083. *
  36084. * @type {Float32Array}
  36085. */
  36086. get buffer() {
  36087. let buffer = this._buffer;
  36088. if ( buffer === null ) {
  36089. const byteLength = this.byteLength;
  36090. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  36091. this._buffer = buffer;
  36092. }
  36093. return buffer;
  36094. }
  36095. /**
  36096. * The byte length of the buffer with correct buffer alignment.
  36097. *
  36098. * @type {Number}
  36099. */
  36100. get byteLength() {
  36101. let offset = 0; // global buffer offset in bytes
  36102. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  36103. const uniform = this.uniforms[ i ];
  36104. const { boundary, itemSize } = uniform;
  36105. // offset within a single chunk in bytes
  36106. const chunkOffset = offset % GPU_CHUNK_BYTES;
  36107. const remainingSizeInChunk = GPU_CHUNK_BYTES - chunkOffset;
  36108. // conformance tests
  36109. if ( chunkOffset !== 0 && ( remainingSizeInChunk - boundary ) < 0 ) {
  36110. // check for chunk overflow
  36111. offset += ( GPU_CHUNK_BYTES - chunkOffset );
  36112. } else if ( chunkOffset % boundary !== 0 ) {
  36113. // check for correct alignment
  36114. offset += ( chunkOffset % boundary );
  36115. }
  36116. uniform.offset = ( offset / this.bytesPerElement );
  36117. offset += ( itemSize * this.bytesPerElement );
  36118. }
  36119. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  36120. }
  36121. /**
  36122. * Updates this group by updating each uniform object of
  36123. * the internal uniform list. The uniform objects check if their
  36124. * values has actually changed so this method only returns
  36125. * `true` if there is a real value change.
  36126. *
  36127. * @return {Boolean} Whether the uniforms have been updated and
  36128. * must be uploaded to the GPU.
  36129. */
  36130. update() {
  36131. let updated = false;
  36132. for ( const uniform of this.uniforms ) {
  36133. if ( this.updateByType( uniform ) === true ) {
  36134. updated = true;
  36135. }
  36136. }
  36137. return updated;
  36138. }
  36139. /**
  36140. * Updates a given uniform by calling an update method matching
  36141. * the uniforms type.
  36142. *
  36143. * @param {Uniform} uniform - The uniform to update.
  36144. * @return {Boolean} Whether the uniform has been updated or not.
  36145. */
  36146. updateByType( uniform ) {
  36147. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  36148. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  36149. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  36150. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  36151. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  36152. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  36153. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  36154. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  36155. }
  36156. /**
  36157. * Updates a given Number uniform.
  36158. *
  36159. * @param {NumberUniform} uniform - The Number uniform.
  36160. * @return {Boolean} Whether the uniform has been updated or not.
  36161. */
  36162. updateNumber( uniform ) {
  36163. let updated = false;
  36164. const a = this.values;
  36165. const v = uniform.getValue();
  36166. const offset = uniform.offset;
  36167. const type = uniform.getType();
  36168. if ( a[ offset ] !== v ) {
  36169. const b = this._getBufferForType( type );
  36170. b[ offset ] = a[ offset ] = v;
  36171. updated = true;
  36172. }
  36173. return updated;
  36174. }
  36175. /**
  36176. * Updates a given Vector2 uniform.
  36177. *
  36178. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  36179. * @return {Boolean} Whether the uniform has been updated or not.
  36180. */
  36181. updateVector2( uniform ) {
  36182. let updated = false;
  36183. const a = this.values;
  36184. const v = uniform.getValue();
  36185. const offset = uniform.offset;
  36186. const type = uniform.getType();
  36187. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  36188. const b = this._getBufferForType( type );
  36189. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36190. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36191. updated = true;
  36192. }
  36193. return updated;
  36194. }
  36195. /**
  36196. * Updates a given Vector3 uniform.
  36197. *
  36198. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  36199. * @return {Boolean} Whether the uniform has been updated or not.
  36200. */
  36201. updateVector3( uniform ) {
  36202. let updated = false;
  36203. const a = this.values;
  36204. const v = uniform.getValue();
  36205. const offset = uniform.offset;
  36206. const type = uniform.getType();
  36207. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  36208. const b = this._getBufferForType( type );
  36209. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36210. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36211. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36212. updated = true;
  36213. }
  36214. return updated;
  36215. }
  36216. /**
  36217. * Updates a given Vector4 uniform.
  36218. *
  36219. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  36220. * @return {Boolean} Whether the uniform has been updated or not.
  36221. */
  36222. updateVector4( uniform ) {
  36223. let updated = false;
  36224. const a = this.values;
  36225. const v = uniform.getValue();
  36226. const offset = uniform.offset;
  36227. const type = uniform.getType();
  36228. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  36229. const b = this._getBufferForType( type );
  36230. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  36231. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  36232. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  36233. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  36234. updated = true;
  36235. }
  36236. return updated;
  36237. }
  36238. /**
  36239. * Updates a given Color uniform.
  36240. *
  36241. * @param {ColorUniform} uniform - The Color uniform.
  36242. * @return {Boolean} Whether the uniform has been updated or not.
  36243. */
  36244. updateColor( uniform ) {
  36245. let updated = false;
  36246. const a = this.values;
  36247. const c = uniform.getValue();
  36248. const offset = uniform.offset;
  36249. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  36250. const b = this.buffer;
  36251. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  36252. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  36253. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  36254. updated = true;
  36255. }
  36256. return updated;
  36257. }
  36258. /**
  36259. * Updates a given Matrix3 uniform.
  36260. *
  36261. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  36262. * @return {Boolean} Whether the uniform has been updated or not.
  36263. */
  36264. updateMatrix3( uniform ) {
  36265. let updated = false;
  36266. const a = this.values;
  36267. const e = uniform.getValue().elements;
  36268. const offset = uniform.offset;
  36269. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  36270. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  36271. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  36272. const b = this.buffer;
  36273. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  36274. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  36275. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  36276. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  36277. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  36278. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  36279. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  36280. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  36281. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  36282. updated = true;
  36283. }
  36284. return updated;
  36285. }
  36286. /**
  36287. * Updates a given Matrix4 uniform.
  36288. *
  36289. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  36290. * @return {Boolean} Whether the uniform has been updated or not.
  36291. */
  36292. updateMatrix4( uniform ) {
  36293. let updated = false;
  36294. const a = this.values;
  36295. const e = uniform.getValue().elements;
  36296. const offset = uniform.offset;
  36297. if ( arraysEqual( a, e, offset ) === false ) {
  36298. const b = this.buffer;
  36299. b.set( e, offset );
  36300. setArray( a, e, offset );
  36301. updated = true;
  36302. }
  36303. return updated;
  36304. }
  36305. /**
  36306. * Returns a typed array that matches the given data type.
  36307. *
  36308. * @param {String} type - The data type.
  36309. * @return {TypedArray} The typed array.
  36310. */
  36311. _getBufferForType( type ) {
  36312. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  36313. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  36314. return this.buffer;
  36315. }
  36316. }
  36317. /**
  36318. * Sets the values of the second array to the first array.
  36319. *
  36320. * @private
  36321. * @param {TypedArray} a - The first array.
  36322. * @param {TypedArray} b - The second array.
  36323. * @param {Number} offset - An index offset for the first array.
  36324. */
  36325. function setArray( a, b, offset ) {
  36326. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36327. a[ offset + i ] = b[ i ];
  36328. }
  36329. }
  36330. /**
  36331. * Returns `true` if the given arrays are equal.
  36332. *
  36333. * @private
  36334. * @param {TypedArray} a - The first array.
  36335. * @param {TypedArray} b - The second array.
  36336. * @param {Number} offset - An index offset for the first array.
  36337. * @return {Boolean} Whether the given arrays are equal or not.
  36338. */
  36339. function arraysEqual( a, b, offset ) {
  36340. for ( let i = 0, l = b.length; i < l; i ++ ) {
  36341. if ( a[ offset + i ] !== b[ i ] ) return false;
  36342. }
  36343. return true;
  36344. }
  36345. let _id$3 = 0;
  36346. /**
  36347. * A special form of uniforms group that represents
  36348. * the individual uniforms as node-based uniforms.
  36349. *
  36350. * @private
  36351. * @augments UniformsGroup
  36352. */
  36353. class NodeUniformsGroup extends UniformsGroup {
  36354. /**
  36355. * Constructs a new node-based uniforms group.
  36356. *
  36357. * @param {String} name - The group's name.
  36358. * @param {UniformGroupNode} groupNode - The uniform group node.
  36359. */
  36360. constructor( name, groupNode ) {
  36361. super( name );
  36362. /**
  36363. * The group's ID.
  36364. *
  36365. * @type {Number}
  36366. */
  36367. this.id = _id$3 ++;
  36368. /**
  36369. * The uniform group node.
  36370. *
  36371. * @type {UniformGroupNode}
  36372. */
  36373. this.groupNode = groupNode;
  36374. /**
  36375. * This flag can be used for type testing.
  36376. *
  36377. * @type {Boolean}
  36378. * @readonly
  36379. * @default true
  36380. */
  36381. this.isNodeUniformsGroup = true;
  36382. }
  36383. }
  36384. let _id$2 = 0;
  36385. /**
  36386. * Represents a sampled texture binding type.
  36387. *
  36388. * @private
  36389. * @augments Binding
  36390. */
  36391. class SampledTexture extends Binding {
  36392. /**
  36393. * Constructs a new sampled texture.
  36394. *
  36395. * @param {String} name - The sampled texture's name.
  36396. * @param {Texture?} texture - The texture this binding is referring to.
  36397. */
  36398. constructor( name, texture ) {
  36399. super( name );
  36400. /**
  36401. * This identifier.
  36402. *
  36403. * @type {Number}
  36404. */
  36405. this.id = _id$2 ++;
  36406. /**
  36407. * The texture this binding is referring to.
  36408. *
  36409. * @type {Texture?}
  36410. */
  36411. this.texture = texture;
  36412. /**
  36413. * The binding's version.
  36414. *
  36415. * @type {Number}
  36416. */
  36417. this.version = texture ? texture.version : 0;
  36418. /**
  36419. * Whether the texture is a storage texture or not.
  36420. *
  36421. * @type {Boolean}
  36422. * @default false
  36423. */
  36424. this.store = false;
  36425. /**
  36426. * The binding's generation which is an additional version
  36427. * qualifier.
  36428. *
  36429. * @type {Number?}
  36430. * @default null
  36431. */
  36432. this.generation = null;
  36433. /**
  36434. * This flag can be used for type testing.
  36435. *
  36436. * @type {Boolean}
  36437. * @readonly
  36438. * @default true
  36439. */
  36440. this.isSampledTexture = true;
  36441. }
  36442. /**
  36443. * Returns `true` whether this binding requires an update for the
  36444. * given generation.
  36445. *
  36446. * @param {Number} generation - The generation.
  36447. * @return {Boolean} Whether an update is required or not.
  36448. */
  36449. needsBindingsUpdate( generation ) {
  36450. const { texture } = this;
  36451. if ( generation !== this.generation ) {
  36452. this.generation = generation;
  36453. return true;
  36454. }
  36455. return texture.isVideoTexture;
  36456. }
  36457. /**
  36458. * Updates the binding.
  36459. *
  36460. * @return {Boolean} Whether the texture has been updated and must be
  36461. * uploaded to the GPU.
  36462. */
  36463. update() {
  36464. const { texture, version } = this;
  36465. if ( version !== texture.version ) {
  36466. this.version = texture.version;
  36467. return true;
  36468. }
  36469. return false;
  36470. }
  36471. }
  36472. /**
  36473. * A special form of sampled texture binding type.
  36474. * It's texture value is managed by a node object.
  36475. *
  36476. * @private
  36477. * @augments SampledTexture
  36478. */
  36479. class NodeSampledTexture extends SampledTexture {
  36480. /**
  36481. * Constructs a new node-based sampled texture.
  36482. *
  36483. * @param {String} name - The textures's name.
  36484. * @param {TextureNode} textureNode - The texture node.
  36485. * @param {UniformGroupNode} groupNode - The uniform group node.
  36486. * @param {String?} [access=null] - The access type.
  36487. */
  36488. constructor( name, textureNode, groupNode, access = null ) {
  36489. super( name, textureNode ? textureNode.value : null );
  36490. /**
  36491. * The texture node.
  36492. *
  36493. * @type {TextureNode}
  36494. */
  36495. this.textureNode = textureNode;
  36496. /**
  36497. * The uniform group node.
  36498. *
  36499. * @type {UniformGroupNode}
  36500. */
  36501. this.groupNode = groupNode;
  36502. /**
  36503. * The access type.
  36504. *
  36505. * @type {String?}
  36506. * @default null
  36507. */
  36508. this.access = access;
  36509. }
  36510. /**
  36511. * Overwrites the default to additionally check if the node value has changed.
  36512. *
  36513. * @param {Number} generation - The generation.
  36514. * @return {Boolean} Whether an update is required or not.
  36515. */
  36516. needsBindingsUpdate( generation ) {
  36517. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  36518. }
  36519. /**
  36520. * Updates the binding.
  36521. *
  36522. * @return {Boolean} Whether the texture has been updated and must be
  36523. * uploaded to the GPU.
  36524. */
  36525. update() {
  36526. const { textureNode } = this;
  36527. if ( this.texture !== textureNode.value ) {
  36528. this.texture = textureNode.value;
  36529. return true;
  36530. }
  36531. return super.update();
  36532. }
  36533. }
  36534. /**
  36535. * A special form of sampled cube texture binding type.
  36536. * It's texture value is managed by a node object.
  36537. *
  36538. * @private
  36539. * @augments NodeSampledTexture
  36540. */
  36541. class NodeSampledCubeTexture extends NodeSampledTexture {
  36542. /**
  36543. * Constructs a new node-based sampled cube texture.
  36544. *
  36545. * @param {String} name - The textures's name.
  36546. * @param {TextureNode} textureNode - The texture node.
  36547. * @param {UniformGroupNode} groupNode - The uniform group node.
  36548. * @param {String?} [access=null] - The access type.
  36549. */
  36550. constructor( name, textureNode, groupNode, access = null ) {
  36551. super( name, textureNode, groupNode, access );
  36552. /**
  36553. * This flag can be used for type testing.
  36554. *
  36555. * @type {Boolean}
  36556. * @readonly
  36557. * @default true
  36558. */
  36559. this.isSampledCubeTexture = true;
  36560. }
  36561. }
  36562. /**
  36563. * A special form of sampled 3D texture binding type.
  36564. * It's texture value is managed by a node object.
  36565. *
  36566. * @private
  36567. * @augments NodeSampledTexture
  36568. */
  36569. class NodeSampledTexture3D extends NodeSampledTexture {
  36570. /**
  36571. * Constructs a new node-based sampled 3D texture.
  36572. *
  36573. * @param {String} name - The textures's name.
  36574. * @param {TextureNode} textureNode - The texture node.
  36575. * @param {UniformGroupNode} groupNode - The uniform group node.
  36576. * @param {String?} [access=null] - The access type.
  36577. */
  36578. constructor( name, textureNode, groupNode, access = null ) {
  36579. super( name, textureNode, groupNode, access );
  36580. /**
  36581. * This flag can be used for type testing.
  36582. *
  36583. * @type {Boolean}
  36584. * @readonly
  36585. * @default true
  36586. */
  36587. this.isSampledTexture3D = true;
  36588. }
  36589. }
  36590. const glslMethods = {
  36591. textureDimensions: 'textureSize',
  36592. equals: 'equal'
  36593. };
  36594. const precisionLib = {
  36595. low: 'lowp',
  36596. medium: 'mediump',
  36597. high: 'highp'
  36598. };
  36599. const supports$1 = {
  36600. swizzleAssign: true,
  36601. storageBuffer: false
  36602. };
  36603. const defaultPrecisions = `
  36604. precision highp float;
  36605. precision highp int;
  36606. precision highp sampler2D;
  36607. precision highp sampler3D;
  36608. precision highp samplerCube;
  36609. precision highp sampler2DArray;
  36610. precision highp usampler2D;
  36611. precision highp usampler3D;
  36612. precision highp usamplerCube;
  36613. precision highp usampler2DArray;
  36614. precision highp isampler2D;
  36615. precision highp isampler3D;
  36616. precision highp isamplerCube;
  36617. precision highp isampler2DArray;
  36618. precision lowp sampler2DShadow;
  36619. `;
  36620. /**
  36621. * A node builder targeting GLSL.
  36622. *
  36623. * This module generates GLSL shader code from node materials and also
  36624. * generates the respective bindings and vertex buffer definitions. These
  36625. * data are later used by the renderer to create render and compute pipelines
  36626. * for render objects.
  36627. *
  36628. * @augments NodeBuilder
  36629. */
  36630. class GLSLNodeBuilder extends NodeBuilder {
  36631. /**
  36632. * Constructs a new GLSL node builder renderer.
  36633. *
  36634. * @param {Object3D} object - The 3D object.
  36635. * @param {Renderer} renderer - The renderer.
  36636. */
  36637. constructor( object, renderer ) {
  36638. super( object, renderer, new GLSLNodeParser() );
  36639. /**
  36640. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  36641. * another dictionary which manages UBOs per group ('render','frame','object').
  36642. *
  36643. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  36644. */
  36645. this.uniformGroups = {};
  36646. /**
  36647. * An array that holds objects defining the varying and attribute data in
  36648. * context of Transform Feedback.
  36649. *
  36650. * @type {Object<String,Map<String,Object>>}
  36651. */
  36652. this.transforms = [];
  36653. /**
  36654. * A dictionary that holds for each shader stage a Map of used extensions.
  36655. *
  36656. * @type {Object<String,Map<String,Object>>}
  36657. */
  36658. this.extensions = {};
  36659. /**
  36660. * A dictionary that holds for each shader stage an Array of used builtins.
  36661. *
  36662. * @type {Object<String,Array<String>>}
  36663. */
  36664. this.builtins = { vertex: [], fragment: [], compute: [] };
  36665. /**
  36666. * Whether comparison in shader code are generated with methods or not.
  36667. *
  36668. * @type {Boolean}
  36669. * @default true
  36670. */
  36671. this.useComparisonMethod = true;
  36672. }
  36673. /**
  36674. * Checks if the given texture requires a manual conversion to the working color space.
  36675. *
  36676. * @param {Texture} texture - The texture to check.
  36677. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  36678. */
  36679. needsToWorkingColorSpace( texture ) {
  36680. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  36681. }
  36682. /**
  36683. * Returns the native shader method name for a given generic name.
  36684. *
  36685. * @param {String} method - The method name to resolve.
  36686. * @return {String} The resolved GLSL method name.
  36687. */
  36688. getMethod( method ) {
  36689. return glslMethods[ method ] || method;
  36690. }
  36691. /**
  36692. * Returns the output struct name. Not relevant for GLSL.
  36693. *
  36694. * @return {String}
  36695. */
  36696. getOutputStructName() {
  36697. return '';
  36698. }
  36699. /**
  36700. * Builds the given shader node.
  36701. *
  36702. * @param {ShaderNodeInternal} shaderNode - The shader node.
  36703. * @return {String} The GLSL function code.
  36704. */
  36705. buildFunctionCode( shaderNode ) {
  36706. const layout = shaderNode.layout;
  36707. const flowData = this.flowShaderNode( shaderNode );
  36708. const parameters = [];
  36709. for ( const input of layout.inputs ) {
  36710. parameters.push( this.getType( input.type ) + ' ' + input.name );
  36711. }
  36712. //
  36713. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  36714. ${ flowData.vars }
  36715. ${ flowData.code }
  36716. return ${ flowData.result };
  36717. }`;
  36718. //
  36719. return code;
  36720. }
  36721. /**
  36722. * Setups the Pixel Buffer Object (PBO) for the given storage
  36723. * buffer node.
  36724. *
  36725. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  36726. */
  36727. setupPBO( storageBufferNode ) {
  36728. const attribute = storageBufferNode.value;
  36729. if ( attribute.pbo === undefined ) {
  36730. const originalArray = attribute.array;
  36731. const numElements = attribute.count * attribute.itemSize;
  36732. const { itemSize } = attribute;
  36733. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  36734. let format = isInteger ? RedIntegerFormat : RedFormat;
  36735. if ( itemSize === 2 ) {
  36736. format = isInteger ? RGIntegerFormat : RGFormat;
  36737. } else if ( itemSize === 3 ) {
  36738. format = isInteger ? RGBIntegerFormat : RGBFormat;
  36739. } else if ( itemSize === 4 ) {
  36740. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  36741. }
  36742. const typeMap = {
  36743. Float32Array: FloatType,
  36744. Uint8Array: UnsignedByteType,
  36745. Uint16Array: UnsignedShortType,
  36746. Uint32Array: UnsignedIntType,
  36747. Int8Array: ByteType,
  36748. Int16Array: ShortType,
  36749. Int32Array: IntType,
  36750. Uint8ClampedArray: UnsignedByteType,
  36751. };
  36752. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  36753. let height = Math.ceil( ( numElements / itemSize ) / width );
  36754. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  36755. const newSize = width * height * itemSize;
  36756. const newArray = new originalArray.constructor( newSize );
  36757. newArray.set( originalArray, 0 );
  36758. attribute.array = newArray;
  36759. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  36760. pboTexture.needsUpdate = true;
  36761. pboTexture.isPBOTexture = true;
  36762. const pbo = new TextureNode( pboTexture, null, null );
  36763. pbo.setPrecision( 'high' );
  36764. attribute.pboNode = pbo;
  36765. attribute.pbo = pbo.value;
  36766. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36767. }
  36768. }
  36769. /**
  36770. * Returns a GLSL snippet that represents the property name of the given node.
  36771. *
  36772. * @param {Node} node - The node.
  36773. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  36774. * @return {String} The property name.
  36775. */
  36776. getPropertyName( node, shaderStage = this.shaderStage ) {
  36777. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  36778. return shaderStage.charAt( 0 ) + '_' + node.name;
  36779. }
  36780. return super.getPropertyName( node, shaderStage );
  36781. }
  36782. /**
  36783. * Setups the Pixel Buffer Object (PBO) for the given storage
  36784. * buffer node.
  36785. *
  36786. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  36787. * @return {String} The property name.
  36788. */
  36789. generatePBO( storageArrayElementNode ) {
  36790. const { node, indexNode } = storageArrayElementNode;
  36791. const attribute = node.value;
  36792. if ( this.renderer.backend.has( attribute ) ) {
  36793. const attributeData = this.renderer.backend.get( attribute );
  36794. attributeData.pbo = attribute.pbo;
  36795. }
  36796. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  36797. const textureName = this.getPropertyName( nodeUniform );
  36798. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  36799. const indexSnippet = indexNode.build( this, 'uint' );
  36800. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  36801. let propertyName = elementNodeData.propertyName;
  36802. if ( propertyName === undefined ) {
  36803. // property element
  36804. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  36805. propertyName = this.getPropertyName( nodeVar );
  36806. // property size
  36807. const bufferNodeData = this.getDataFromNode( node );
  36808. let propertySizeName = bufferNodeData.propertySizeName;
  36809. if ( propertySizeName === undefined ) {
  36810. propertySizeName = propertyName + 'Size';
  36811. this.getVarFromNode( node, propertySizeName, 'uint' );
  36812. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  36813. bufferNodeData.propertySizeName = propertySizeName;
  36814. }
  36815. //
  36816. const { itemSize } = attribute;
  36817. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  36818. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  36819. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  36820. //
  36821. let prefix = 'vec4';
  36822. if ( attribute.pbo.type === UnsignedIntType ) {
  36823. prefix = 'uvec4';
  36824. } else if ( attribute.pbo.type === IntType ) {
  36825. prefix = 'ivec4';
  36826. }
  36827. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  36828. elementNodeData.propertyName = propertyName;
  36829. }
  36830. return propertyName;
  36831. }
  36832. /**
  36833. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  36834. *
  36835. * @param {Texture} texture - The texture.
  36836. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36837. * @param {String} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36838. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  36839. * @param {String} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  36840. * @return {String} The GLSL snippet.
  36841. */
  36842. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  36843. if ( depthSnippet ) {
  36844. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  36845. } else {
  36846. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  36847. }
  36848. }
  36849. /**
  36850. * Generates the GLSL snippet for sampling/loading the given texture.
  36851. *
  36852. * @param {Texture} texture - The texture.
  36853. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36854. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36855. * @param {String?} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  36856. * @return {String} The GLSL snippet.
  36857. */
  36858. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  36859. if ( texture.isDepthTexture ) {
  36860. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  36861. } else {
  36862. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  36863. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  36864. }
  36865. }
  36866. /**
  36867. * Generates the GLSL snippet when sampling textures with explicit mip level.
  36868. *
  36869. * @param {Texture} texture - The texture.
  36870. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36871. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36872. * @param {String} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  36873. * @return {String} The GLSL snippet.
  36874. */
  36875. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  36876. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  36877. }
  36878. /**
  36879. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  36880. *
  36881. * @param {Texture} texture - The texture.
  36882. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36883. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36884. * @param {String} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  36885. * @return {String} The GLSL snippet.
  36886. */
  36887. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  36888. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  36889. }
  36890. /**
  36891. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  36892. *
  36893. * @param {Texture} texture - The texture.
  36894. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36895. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36896. * @param {Array<String>} gradSnippet - An array holding both gradient GLSL snippets.
  36897. * @return {String} The GLSL snippet.
  36898. */
  36899. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  36900. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  36901. }
  36902. /**
  36903. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  36904. * against a reference value.
  36905. *
  36906. * @param {Texture} texture - The texture.
  36907. * @param {String} textureProperty - The name of the texture uniform in the shader.
  36908. * @param {String} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  36909. * @param {String} compareSnippet - A GLSL snippet that represents the reference value.
  36910. * @param {String?} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  36911. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  36912. * @return {String} The GLSL snippet.
  36913. */
  36914. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  36915. if ( shaderStage === 'fragment' ) {
  36916. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  36917. } else {
  36918. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  36919. }
  36920. }
  36921. /**
  36922. * Returns the variables of the given shader stage as a GLSL string.
  36923. *
  36924. * @param {String} shaderStage - The shader stage.
  36925. * @return {String} The GLSL snippet that defines the variables.
  36926. */
  36927. getVars( shaderStage ) {
  36928. const snippets = [];
  36929. const vars = this.vars[ shaderStage ];
  36930. if ( vars !== undefined ) {
  36931. for ( const variable of vars ) {
  36932. snippets.push( `${ this.getVar( variable.type, variable.name ) };` );
  36933. }
  36934. }
  36935. return snippets.join( '\n\t' );
  36936. }
  36937. /**
  36938. * Returns the uniforms of the given shader stage as a GLSL string.
  36939. *
  36940. * @param {String} shaderStage - The shader stage.
  36941. * @return {String} The GLSL snippet that defines the uniforms.
  36942. */
  36943. getUniforms( shaderStage ) {
  36944. const uniforms = this.uniforms[ shaderStage ];
  36945. const bindingSnippets = [];
  36946. const uniformGroups = {};
  36947. for ( const uniform of uniforms ) {
  36948. let snippet = null;
  36949. let group = false;
  36950. if ( uniform.type === 'texture' ) {
  36951. const texture = uniform.node.value;
  36952. let typePrefix = '';
  36953. if ( texture.isDataTexture === true ) {
  36954. if ( texture.type === UnsignedIntType ) {
  36955. typePrefix = 'u';
  36956. } else if ( texture.type === IntType ) {
  36957. typePrefix = 'i';
  36958. }
  36959. }
  36960. if ( texture.compareFunction ) {
  36961. snippet = `sampler2DShadow ${ uniform.name };`;
  36962. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  36963. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  36964. } else {
  36965. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  36966. }
  36967. } else if ( uniform.type === 'cubeTexture' ) {
  36968. snippet = `samplerCube ${ uniform.name };`;
  36969. } else if ( uniform.type === 'texture3D' ) {
  36970. snippet = `sampler3D ${ uniform.name };`;
  36971. } else if ( uniform.type === 'buffer' ) {
  36972. const bufferNode = uniform.node;
  36973. const bufferType = this.getType( bufferNode.bufferType );
  36974. const bufferCount = bufferNode.bufferCount;
  36975. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  36976. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  36977. } else {
  36978. const vectorType = this.getVectorType( uniform.type );
  36979. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  36980. group = true;
  36981. }
  36982. const precision = uniform.node.precision;
  36983. if ( precision !== null ) {
  36984. snippet = precisionLib[ precision ] + ' ' + snippet;
  36985. }
  36986. if ( group ) {
  36987. snippet = '\t' + snippet;
  36988. const groupName = uniform.groupNode.name;
  36989. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  36990. groupSnippets.push( snippet );
  36991. } else {
  36992. snippet = 'uniform ' + snippet;
  36993. bindingSnippets.push( snippet );
  36994. }
  36995. }
  36996. let output = '';
  36997. for ( const name in uniformGroups ) {
  36998. const groupSnippets = uniformGroups[ name ];
  36999. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  37000. }
  37001. output += bindingSnippets.join( '\n' );
  37002. return output;
  37003. }
  37004. /**
  37005. * Returns the type for a given buffer attribute.
  37006. *
  37007. * @param {BufferAttribute} attribute - The buffer attribute.
  37008. * @return {String} The type.
  37009. */
  37010. getTypeFromAttribute( attribute ) {
  37011. let nodeType = super.getTypeFromAttribute( attribute );
  37012. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  37013. let dataAttribute = attribute;
  37014. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  37015. const array = dataAttribute.array;
  37016. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  37017. nodeType = nodeType.slice( 1 );
  37018. }
  37019. }
  37020. return nodeType;
  37021. }
  37022. /**
  37023. * Returns the shader attributes of the given shader stage as a GLSL string.
  37024. *
  37025. * @param {String} shaderStage - The shader stage.
  37026. * @return {String} The GLSL snippet that defines the shader attributes.
  37027. */
  37028. getAttributes( shaderStage ) {
  37029. let snippet = '';
  37030. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37031. const attributes = this.getAttributesArray();
  37032. let location = 0;
  37033. for ( const attribute of attributes ) {
  37034. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  37035. }
  37036. }
  37037. return snippet;
  37038. }
  37039. /**
  37040. * Returns the members of the given struct type node as a GLSL string.
  37041. *
  37042. * @param {StructTypeNode} struct - The struct type node.
  37043. * @return {String} The GLSL snippet that defines the struct members.
  37044. */
  37045. getStructMembers( struct ) {
  37046. const snippets = [];
  37047. const members = struct.getMemberTypes();
  37048. for ( let i = 0; i < members.length; i ++ ) {
  37049. const member = members[ i ];
  37050. snippets.push( `layout( location = ${i} ) out ${ member} m${i};` );
  37051. }
  37052. return snippets.join( '\n' );
  37053. }
  37054. /**
  37055. * Returns the structs of the given shader stage as a GLSL string.
  37056. *
  37057. * @param {String} shaderStage - The shader stage.
  37058. * @return {String} The GLSL snippet that defines the structs.
  37059. */
  37060. getStructs( shaderStage ) {
  37061. const snippets = [];
  37062. const structs = this.structs[ shaderStage ];
  37063. if ( structs.length === 0 ) {
  37064. return 'layout( location = 0 ) out vec4 fragColor;\n';
  37065. }
  37066. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  37067. const struct = structs[ index ];
  37068. let snippet = '\n';
  37069. snippet += this.getStructMembers( struct );
  37070. snippet += '\n';
  37071. snippets.push( snippet );
  37072. }
  37073. return snippets.join( '\n\n' );
  37074. }
  37075. /**
  37076. * Returns the varyings of the given shader stage as a GLSL string.
  37077. *
  37078. * @param {String} shaderStage - The shader stage.
  37079. * @return {String} The GLSL snippet that defines the varyings.
  37080. */
  37081. getVaryings( shaderStage ) {
  37082. let snippet = '';
  37083. const varyings = this.varyings;
  37084. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  37085. for ( const varying of varyings ) {
  37086. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  37087. const type = this.getType( varying.type );
  37088. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37089. snippet += `${flat}${varying.needsInterpolation ? 'out' : '/*out*/'} ${type} ${varying.name};\n`;
  37090. }
  37091. } else if ( shaderStage === 'fragment' ) {
  37092. for ( const varying of varyings ) {
  37093. if ( varying.needsInterpolation ) {
  37094. const type = this.getType( varying.type );
  37095. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  37096. snippet += `${flat}in ${type} ${varying.name};\n`;
  37097. }
  37098. }
  37099. }
  37100. for ( const builtin of this.builtins[ shaderStage ] ) {
  37101. snippet += `${builtin};\n`;
  37102. }
  37103. return snippet;
  37104. }
  37105. /**
  37106. * Returns the vertex index builtin.
  37107. *
  37108. * @return {String} The vertex index.
  37109. */
  37110. getVertexIndex() {
  37111. return 'uint( gl_VertexID )';
  37112. }
  37113. /**
  37114. * Returns the instance index builtin.
  37115. *
  37116. * @return {String} The instance index.
  37117. */
  37118. getInstanceIndex() {
  37119. return 'uint( gl_InstanceID )';
  37120. }
  37121. /**
  37122. * Returns the invocation local index builtin.
  37123. *
  37124. * @return {String} The invocation local index.
  37125. */
  37126. getInvocationLocalIndex() {
  37127. const workgroupSize = this.object.workgroupSize;
  37128. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  37129. return `uint( gl_InstanceID ) % ${size}u`;
  37130. }
  37131. /**
  37132. * Returns the draw index builtin.
  37133. *
  37134. * @return {String?} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  37135. */
  37136. getDrawIndex() {
  37137. const extensions = this.renderer.backend.extensions;
  37138. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  37139. return 'uint( gl_DrawID )';
  37140. }
  37141. return null;
  37142. }
  37143. /**
  37144. * Returns the front facing builtin.
  37145. *
  37146. * @return {String} The front facing builtin.
  37147. */
  37148. getFrontFacing() {
  37149. return 'gl_FrontFacing';
  37150. }
  37151. /**
  37152. * Returns the frag coord builtin.
  37153. *
  37154. * @return {String} The frag coord builtin.
  37155. */
  37156. getFragCoord() {
  37157. return 'gl_FragCoord.xy';
  37158. }
  37159. /**
  37160. * Returns the frag depth builtin.
  37161. *
  37162. * @return {String} The frag depth builtin.
  37163. */
  37164. getFragDepth() {
  37165. return 'gl_FragDepth';
  37166. }
  37167. /**
  37168. * Enables the given extension.
  37169. *
  37170. * @param {String} name - The extension name.
  37171. * @param {String} behavior - The extension behavior.
  37172. * @param {String} [shaderStage=this.shaderStage] - The shader stage.
  37173. */
  37174. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  37175. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  37176. if ( map.has( name ) === false ) {
  37177. map.set( name, {
  37178. name,
  37179. behavior
  37180. } );
  37181. }
  37182. }
  37183. /**
  37184. * Returns the enabled extensions of the given shader stage as a GLSL string.
  37185. *
  37186. * @param {String} shaderStage - The shader stage.
  37187. * @return {String} The GLSL snippet that defines the enabled extensions.
  37188. */
  37189. getExtensions( shaderStage ) {
  37190. const snippets = [];
  37191. if ( shaderStage === 'vertex' ) {
  37192. const ext = this.renderer.backend.extensions;
  37193. const isBatchedMesh = this.object.isBatchedMesh;
  37194. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  37195. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  37196. }
  37197. }
  37198. const extensions = this.extensions[ shaderStage ];
  37199. if ( extensions !== undefined ) {
  37200. for ( const { name, behavior } of extensions.values() ) {
  37201. snippets.push( `#extension ${name} : ${behavior}` );
  37202. }
  37203. }
  37204. return snippets.join( '\n' );
  37205. }
  37206. /**
  37207. * Returns the clip distances builtin.
  37208. *
  37209. * @return {String} The clip distances builtin.
  37210. */
  37211. getClipDistance() {
  37212. return 'gl_ClipDistance';
  37213. }
  37214. /**
  37215. * Whether the requested feature is available or not.
  37216. *
  37217. * @param {String} name - The requested feature.
  37218. * @return {Boolean} Whether the requested feature is supported or not.
  37219. */
  37220. isAvailable( name ) {
  37221. let result = supports$1[ name ];
  37222. if ( result === undefined ) {
  37223. let extensionName;
  37224. result = false;
  37225. switch ( name ) {
  37226. case 'float32Filterable':
  37227. extensionName = 'OES_texture_float_linear';
  37228. break;
  37229. case 'clipDistance':
  37230. extensionName = 'WEBGL_clip_cull_distance';
  37231. break;
  37232. }
  37233. if ( extensionName !== undefined ) {
  37234. const extensions = this.renderer.backend.extensions;
  37235. if ( extensions.has( extensionName ) ) {
  37236. extensions.get( extensionName );
  37237. result = true;
  37238. }
  37239. }
  37240. supports$1[ name ] = result;
  37241. }
  37242. return result;
  37243. }
  37244. /**
  37245. * Whether to flip texture data along its vertical axis or not.
  37246. *
  37247. * @return {Boolean} Returns always `true` in context of GLSL.
  37248. */
  37249. isFlipY() {
  37250. return true;
  37251. }
  37252. /**
  37253. * Enables hardware clipping.
  37254. *
  37255. * @param {String} planeCount - The clipping plane count.
  37256. */
  37257. enableHardwareClipping( planeCount ) {
  37258. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  37259. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  37260. }
  37261. /**
  37262. * Registers a transform in context of Transform Feedback.
  37263. *
  37264. * @param {String} varyingName - The varying name.
  37265. * @param {AttributeNode} attributeNode - The attribute node.
  37266. */
  37267. registerTransform( varyingName, attributeNode ) {
  37268. this.transforms.push( { varyingName, attributeNode } );
  37269. }
  37270. /**
  37271. * Returns the transforms of the given shader stage as a GLSL string.
  37272. *
  37273. * @param {String} shaderStage - The shader stage.
  37274. * @return {String} The GLSL snippet that defines the transforms.
  37275. */
  37276. getTransforms( /* shaderStage */ ) {
  37277. const transforms = this.transforms;
  37278. let snippet = '';
  37279. for ( let i = 0; i < transforms.length; i ++ ) {
  37280. const transform = transforms[ i ];
  37281. const attributeName = this.getPropertyName( transform.attributeNode );
  37282. snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  37283. }
  37284. return snippet;
  37285. }
  37286. /**
  37287. * Returns a GLSL struct based on the given name and variables.
  37288. *
  37289. * @private
  37290. * @param {String} name - The struct name.
  37291. * @param {String} vars - The struct variables.
  37292. * @return {String} The GLSL snippet representing a struct.
  37293. */
  37294. _getGLSLUniformStruct( name, vars ) {
  37295. return `
  37296. layout( std140 ) uniform ${name} {
  37297. ${vars}
  37298. };`;
  37299. }
  37300. /**
  37301. * Returns a GLSL vertex shader based on the given shader data.
  37302. *
  37303. * @private
  37304. * @param {Object} shaderData - The shader data.
  37305. * @return {String} The vertex shader.
  37306. */
  37307. _getGLSLVertexCode( shaderData ) {
  37308. return `#version 300 es
  37309. ${ this.getSignature() }
  37310. // extensions
  37311. ${shaderData.extensions}
  37312. // precision
  37313. ${ defaultPrecisions }
  37314. // uniforms
  37315. ${shaderData.uniforms}
  37316. // varyings
  37317. ${shaderData.varyings}
  37318. // attributes
  37319. ${shaderData.attributes}
  37320. // codes
  37321. ${shaderData.codes}
  37322. void main() {
  37323. // vars
  37324. ${shaderData.vars}
  37325. // transforms
  37326. ${shaderData.transforms}
  37327. // flow
  37328. ${shaderData.flow}
  37329. gl_PointSize = 1.0;
  37330. }
  37331. `;
  37332. }
  37333. /**
  37334. * Returns a GLSL fragment shader based on the given shader data.
  37335. *
  37336. * @private
  37337. * @param {Object} shaderData - The shader data.
  37338. * @return {String} The vertex shader.
  37339. */
  37340. _getGLSLFragmentCode( shaderData ) {
  37341. return `#version 300 es
  37342. ${ this.getSignature() }
  37343. // precision
  37344. ${ defaultPrecisions }
  37345. // uniforms
  37346. ${shaderData.uniforms}
  37347. // varyings
  37348. ${shaderData.varyings}
  37349. // codes
  37350. ${shaderData.codes}
  37351. ${shaderData.structs}
  37352. void main() {
  37353. // vars
  37354. ${shaderData.vars}
  37355. // flow
  37356. ${shaderData.flow}
  37357. }
  37358. `;
  37359. }
  37360. /**
  37361. * Controls the code build of the shader stages.
  37362. */
  37363. buildCode() {
  37364. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  37365. this.sortBindingGroups();
  37366. for ( const shaderStage in shadersData ) {
  37367. let flow = '// code\n\n';
  37368. flow += this.flowCode[ shaderStage ];
  37369. const flowNodes = this.flowNodes[ shaderStage ];
  37370. const mainNode = flowNodes[ flowNodes.length - 1 ];
  37371. for ( const node of flowNodes ) {
  37372. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  37373. const slotName = node.name;
  37374. if ( slotName ) {
  37375. if ( flow.length > 0 ) flow += '\n';
  37376. flow += `\t// flow -> ${ slotName }\n\t`;
  37377. }
  37378. flow += `${ flowSlotData.code }\n\t`;
  37379. if ( node === mainNode && shaderStage !== 'compute' ) {
  37380. flow += '// result\n\t';
  37381. if ( shaderStage === 'vertex' ) {
  37382. flow += 'gl_Position = ';
  37383. flow += `${ flowSlotData.result };`;
  37384. } else if ( shaderStage === 'fragment' ) {
  37385. if ( ! node.outputNode.isOutputStructNode ) {
  37386. flow += 'fragColor = ';
  37387. flow += `${ flowSlotData.result };`;
  37388. }
  37389. }
  37390. }
  37391. }
  37392. const stageData = shadersData[ shaderStage ];
  37393. stageData.extensions = this.getExtensions( shaderStage );
  37394. stageData.uniforms = this.getUniforms( shaderStage );
  37395. stageData.attributes = this.getAttributes( shaderStage );
  37396. stageData.varyings = this.getVaryings( shaderStage );
  37397. stageData.vars = this.getVars( shaderStage );
  37398. stageData.structs = this.getStructs( shaderStage );
  37399. stageData.codes = this.getCodes( shaderStage );
  37400. stageData.transforms = this.getTransforms( shaderStage );
  37401. stageData.flow = flow;
  37402. }
  37403. if ( this.material !== null ) {
  37404. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  37405. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  37406. } else {
  37407. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  37408. }
  37409. }
  37410. /**
  37411. * This method is one of the more important ones since it's responsible
  37412. * for generating a matching binding instance for the given uniform node.
  37413. *
  37414. * These bindings are later used in the renderer to create bind groups
  37415. * and layouts.
  37416. *
  37417. * @param {UniformNode} node - The uniform node.
  37418. * @param {String} type - The node data type.
  37419. * @param {String} shaderStage - The shader stage.
  37420. * @param {String?} [name=null] - An optional uniform name.
  37421. * @return {NodeUniform} The node uniform object.
  37422. */
  37423. getUniformFromNode( node, type, shaderStage, name = null ) {
  37424. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  37425. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  37426. let uniformGPU = nodeData.uniformGPU;
  37427. if ( uniformGPU === undefined ) {
  37428. const group = node.groupNode;
  37429. const groupName = group.name;
  37430. const bindings = this.getBindGroupArray( groupName, shaderStage );
  37431. if ( type === 'texture' ) {
  37432. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  37433. bindings.push( uniformGPU );
  37434. } else if ( type === 'cubeTexture' ) {
  37435. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  37436. bindings.push( uniformGPU );
  37437. } else if ( type === 'texture3D' ) {
  37438. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  37439. bindings.push( uniformGPU );
  37440. } else if ( type === 'buffer' ) {
  37441. node.name = `NodeBuffer_${ node.id }`;
  37442. uniformNode.name = `buffer${ node.id }`;
  37443. const buffer = new NodeUniformBuffer( node, group );
  37444. buffer.name = node.name;
  37445. bindings.push( buffer );
  37446. uniformGPU = buffer;
  37447. } else {
  37448. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  37449. let uniformsGroup = uniformsStage[ groupName ];
  37450. if ( uniformsGroup === undefined ) {
  37451. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  37452. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  37453. uniformsStage[ groupName ] = uniformsGroup;
  37454. bindings.push( uniformsGroup );
  37455. }
  37456. uniformGPU = this.getNodeUniform( uniformNode, type );
  37457. uniformsGroup.addUniform( uniformGPU );
  37458. }
  37459. nodeData.uniformGPU = uniformGPU;
  37460. }
  37461. return uniformNode;
  37462. }
  37463. }
  37464. let _vector2 = null;
  37465. let _color4 = null;
  37466. /**
  37467. * Most of the rendering related logic is implemented in the
  37468. * {@link module:Renderer} module and related management components.
  37469. * Sometimes it is required though to execute commands which are
  37470. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  37471. * This abstract base class defines an interface that encapsulates
  37472. * all backend-related logic. Derived classes for each backend must
  37473. * implement the interface.
  37474. *
  37475. * @abstract
  37476. * @private
  37477. */
  37478. class Backend {
  37479. /**
  37480. * Constructs a new backend.
  37481. *
  37482. * @param {Object} parameters - An object holding parameters for the backend.
  37483. */
  37484. constructor( parameters = {} ) {
  37485. /**
  37486. * The parameters of the backend.
  37487. *
  37488. * @type {Object}
  37489. */
  37490. this.parameters = Object.assign( {}, parameters );
  37491. /**
  37492. * This weak map holds backend-specific data of objects
  37493. * like textures, attributes or render targets.
  37494. *
  37495. * @type {WeakMap}
  37496. */
  37497. this.data = new WeakMap();
  37498. /**
  37499. * A reference to the renderer.
  37500. *
  37501. * @type {Renderer?}
  37502. * @default null
  37503. */
  37504. this.renderer = null;
  37505. /**
  37506. * A reference to the canvas element the renderer is drawing to.
  37507. *
  37508. * @type {(HTMLCanvasElement|OffscreenCanvas)?}
  37509. * @default null
  37510. */
  37511. this.domElement = null;
  37512. }
  37513. /**
  37514. * Initializes the backend so it is ready for usage. Concrete backends
  37515. * are supposed to implement their rendering context creation and related
  37516. * operations in this method.
  37517. *
  37518. * @async
  37519. * @param {Renderer} renderer - The renderer.
  37520. * @return {Promise} A Promise that resolves when the backend has been initialized.
  37521. */
  37522. async init( renderer ) {
  37523. this.renderer = renderer;
  37524. }
  37525. /**
  37526. * The coordinate system of the backend.
  37527. *
  37528. * @abstract
  37529. * @type {Number}
  37530. * @readonly
  37531. */
  37532. get coordinateSystem() {}
  37533. // render context
  37534. /**
  37535. * This method is executed at the beginning of a render call and
  37536. * can be used by the backend to prepare the state for upcoming
  37537. * draw calls.
  37538. *
  37539. * @abstract
  37540. * @param {RenderContext} renderContext - The render context.
  37541. */
  37542. beginRender( /*renderContext*/ ) {}
  37543. /**
  37544. * This method is executed at the end of a render call and
  37545. * can be used by the backend to finalize work after draw
  37546. * calls.
  37547. *
  37548. * @abstract
  37549. * @param {RenderContext} renderContext - The render context.
  37550. */
  37551. finishRender( /*renderContext*/ ) {}
  37552. /**
  37553. * This method is executed at the beginning of a compute call and
  37554. * can be used by the backend to prepare the state for upcoming
  37555. * compute tasks.
  37556. *
  37557. * @abstract
  37558. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37559. */
  37560. beginCompute( /*computeGroup*/ ) {}
  37561. /**
  37562. * This method is executed at the end of a compute call and
  37563. * can be used by the backend to finalize work after compute
  37564. * tasks.
  37565. *
  37566. * @abstract
  37567. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  37568. */
  37569. finishCompute( /*computeGroup*/ ) {}
  37570. // render object
  37571. /**
  37572. * Executes a draw command for the given render object.
  37573. *
  37574. * @abstract
  37575. * @param {RenderObject} renderObject - The render object to draw.
  37576. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  37577. */
  37578. draw( /*renderObject, info*/ ) { }
  37579. // compute node
  37580. /**
  37581. * Executes a compute command for the given compute node.
  37582. *
  37583. * @abstract
  37584. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  37585. * @param {Node} computeNode - The compute node.
  37586. * @param {Array<BindGroup>} bindings - The bindings.
  37587. * @param {ComputePipeline} computePipeline - The compute pipeline.
  37588. */
  37589. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  37590. // program
  37591. /**
  37592. * Creates a shader program from the given programmable stage.
  37593. *
  37594. * @abstract
  37595. * @param {ProgrammableStage} program - The programmable stage.
  37596. */
  37597. createProgram( /*program*/ ) { }
  37598. /**
  37599. * Destroys the shader program of the given programmable stage.
  37600. *
  37601. * @abstract
  37602. * @param {ProgrammableStage} program - The programmable stage.
  37603. */
  37604. destroyProgram( /*program*/ ) { }
  37605. // bindings
  37606. /**
  37607. * Creates bindings from the given bind group definition.
  37608. *
  37609. * @abstract
  37610. * @param {BindGroup} bindGroup - The bind group.
  37611. * @param {Array<BindGroup>} bindings - Array of bind groups.
  37612. * @param {Number} cacheIndex - The cache index.
  37613. * @param {Number} version - The version.
  37614. */
  37615. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  37616. /**
  37617. * Updates the given bind group definition.
  37618. *
  37619. * @abstract
  37620. * @param {BindGroup} bindGroup - The bind group.
  37621. * @param {Array<BindGroup>} bindings - Array of bind groups.
  37622. * @param {Number} cacheIndex - The cache index.
  37623. * @param {Number} version - The version.
  37624. */
  37625. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  37626. /**
  37627. * Updates a buffer binding.
  37628. *
  37629. * @abstract
  37630. * @param {Buffer} binding - The buffer binding to update.
  37631. */
  37632. updateBinding( /*binding*/ ) { }
  37633. // pipeline
  37634. /**
  37635. * Creates a render pipeline for the given render object.
  37636. *
  37637. * @abstract
  37638. * @param {RenderObject} renderObject - The render object.
  37639. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  37640. */
  37641. createRenderPipeline( /*renderObject, promises*/ ) { }
  37642. /**
  37643. * Creates a compute pipeline for the given compute node.
  37644. *
  37645. * @abstract
  37646. * @param {ComputePipeline} computePipeline - The compute pipeline.
  37647. * @param {Array<BindGroup>} bindings - The bindings.
  37648. */
  37649. createComputePipeline( /*computePipeline, bindings*/ ) { }
  37650. // cache key
  37651. /**
  37652. * Returns `true` if the render pipeline requires an update.
  37653. *
  37654. * @abstract
  37655. * @param {RenderObject} renderObject - The render object.
  37656. * @return {Boolean} Whether the render pipeline requires an update or not.
  37657. */
  37658. needsRenderUpdate( /*renderObject*/ ) { }
  37659. /**
  37660. * Returns a cache key that is used to identify render pipelines.
  37661. *
  37662. * @abstract
  37663. * @param {RenderObject} renderObject - The render object.
  37664. * @return {String} The cache key.
  37665. */
  37666. getRenderCacheKey( /*renderObject*/ ) { }
  37667. // node builder
  37668. /**
  37669. * Returns a node builder for the given render object.
  37670. *
  37671. * @abstract
  37672. * @param {RenderObject} renderObject - The render object.
  37673. * @param {Renderer} renderer - The renderer.
  37674. * @return {NodeBuilder} The node builder.
  37675. */
  37676. createNodeBuilder( /*renderObject, renderer*/ ) { }
  37677. // textures
  37678. /**
  37679. * Creates a GPU sampler for the given texture.
  37680. *
  37681. * @abstract
  37682. * @param {Texture} texture - The texture to create the sampler for.
  37683. */
  37684. createSampler( /*texture*/ ) { }
  37685. /**
  37686. * Destroys the GPU sampler for the given texture.
  37687. *
  37688. * @abstract
  37689. * @param {Texture} texture - The texture to destroy the sampler for.
  37690. */
  37691. destroySampler( /*texture*/ ) {}
  37692. /**
  37693. * Creates a default texture for the given texture that can be used
  37694. * as a placeholder until the actual texture is ready for usage.
  37695. *
  37696. * @abstract
  37697. * @param {Texture} texture - The texture to create a default texture for.
  37698. */
  37699. createDefaultTexture( /*texture*/ ) { }
  37700. /**
  37701. * Defines a texture on the GPU for the given texture object.
  37702. *
  37703. * @abstract
  37704. * @param {Texture} texture - The texture.
  37705. * @param {Object} [options={}] - Optional configuration parameter.
  37706. */
  37707. createTexture( /*texture, options={}*/ ) { }
  37708. /**
  37709. * Uploads the updated texture data to the GPU.
  37710. *
  37711. * @abstract
  37712. * @param {Texture} texture - The texture.
  37713. * @param {Object} [options={}] - Optional configuration parameter.
  37714. */
  37715. updateTexture( /*texture, options = {}*/ ) { }
  37716. /**
  37717. * Generates mipmaps for the given texture.
  37718. *
  37719. * @abstract
  37720. * @param {Texture} texture - The texture.
  37721. */
  37722. generateMipmaps( /*texture*/ ) { }
  37723. /**
  37724. * Destroys the GPU data for the given texture object.
  37725. *
  37726. * @abstract
  37727. * @param {Texture} texture - The texture.
  37728. */
  37729. destroyTexture( /*texture*/ ) { }
  37730. /**
  37731. * Returns texture data as a typed array.
  37732. *
  37733. * @abstract
  37734. * @async
  37735. * @param {Texture} texture - The texture to copy.
  37736. * @param {Number} x - The x coordinate of the copy origin.
  37737. * @param {Number} y - The y coordinate of the copy origin.
  37738. * @param {Number} width - The width of the copy.
  37739. * @param {Number} height - The height of the copy.
  37740. * @param {Number} faceIndex - The face index.
  37741. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  37742. */
  37743. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  37744. /**
  37745. * Copies data of the given source texture to the given destination texture.
  37746. *
  37747. * @abstract
  37748. * @param {Texture} srcTexture - The source texture.
  37749. * @param {Texture} dstTexture - The destination texture.
  37750. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  37751. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  37752. * @param {Number} [level=0] - The mip level to copy.
  37753. */
  37754. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0*/ ) {}
  37755. /**
  37756. * Copies the current bound framebuffer to the given texture.
  37757. *
  37758. * @abstract
  37759. * @param {Texture} texture - The destination texture.
  37760. * @param {RenderContext} renderContext - The render context.
  37761. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  37762. */
  37763. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  37764. // attributes
  37765. /**
  37766. * Creates the GPU buffer of a shader attribute.
  37767. *
  37768. * @abstract
  37769. * @param {BufferAttribute} attribute - The buffer attribute.
  37770. */
  37771. createAttribute( /*attribute*/ ) { }
  37772. /**
  37773. * Creates the GPU buffer of an indexed shader attribute.
  37774. *
  37775. * @abstract
  37776. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  37777. */
  37778. createIndexAttribute( /*attribute*/ ) { }
  37779. /**
  37780. * Creates the GPU buffer of a storage attribute.
  37781. *
  37782. * @abstract
  37783. * @param {BufferAttribute} attribute - The buffer attribute.
  37784. */
  37785. createStorageAttribute( /*attribute*/ ) { }
  37786. /**
  37787. * Updates the GPU buffer of a shader attribute.
  37788. *
  37789. * @abstract
  37790. * @param {BufferAttribute} attribute - The buffer attribute to update.
  37791. */
  37792. updateAttribute( /*attribute*/ ) { }
  37793. /**
  37794. * Destroys the GPU buffer of a shader attribute.
  37795. *
  37796. * @abstract
  37797. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  37798. */
  37799. destroyAttribute( /*attribute*/ ) { }
  37800. // canvas
  37801. /**
  37802. * Returns the backend's rendering context.
  37803. *
  37804. * @abstract
  37805. * @return {Object} The rendering context.
  37806. */
  37807. getContext() { }
  37808. /**
  37809. * Backends can use this method if they have to run
  37810. * logic when the renderer gets resized.
  37811. *
  37812. * @abstract
  37813. */
  37814. updateSize() { }
  37815. /**
  37816. * Updates the viewport with the values from the given render context.
  37817. *
  37818. * @abstract
  37819. * @param {RenderContext} renderContext - The render context.
  37820. */
  37821. updateViewport( /*renderContext*/ ) {}
  37822. // utils
  37823. /**
  37824. * Returns `true` if the given 3D object is fully occluded by other
  37825. * 3D objects in the scene. Backends must implement this method by using
  37826. * a Occlusion Query API.
  37827. *
  37828. * @abstract
  37829. * @param {RenderContext} renderContext - The render context.
  37830. * @param {Object3D} object - The 3D object to test.
  37831. * @return {Boolean} Whether the 3D object is fully occluded or not.
  37832. */
  37833. isOccluded( /*renderContext, object*/ ) {}
  37834. /**
  37835. * Resolves the time stamp for the given render context and type.
  37836. *
  37837. * @async
  37838. * @abstract
  37839. * @param {RenderContext} renderContext - The render context.
  37840. * @param {String} type - The render context.
  37841. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  37842. */
  37843. async resolveTimestampAsync( /*renderContext, type*/ ) { }
  37844. /**
  37845. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  37846. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  37847. *
  37848. * @async
  37849. * @abstract
  37850. * @return {Promise} A Promise that resolves when synchronization has been finished.
  37851. */
  37852. async waitForGPU() {}
  37853. /**
  37854. * This method performs a readback operation by moving buffer data from
  37855. * a storage buffer attribute from the GPU to the CPU.
  37856. *
  37857. * @async
  37858. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37859. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37860. */
  37861. async getArrayBufferAsync( /* attribute */ ) {}
  37862. /**
  37863. * Checks if the given feature is supported by the backend.
  37864. *
  37865. * @async
  37866. * @abstract
  37867. * @param {String} name - The feature's name.
  37868. * @return {Promise<Boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  37869. */
  37870. async hasFeatureAsync( /*name*/ ) { }
  37871. /**
  37872. * Checks if the given feature is supported by the backend.
  37873. *
  37874. * @abstract
  37875. * @param {String} name - The feature's name.
  37876. * @return {Boolean} Whether the feature is supported or not.
  37877. */
  37878. hasFeature( /*name*/ ) {}
  37879. /**
  37880. * Returns the maximum anisotropy texture filtering value.
  37881. *
  37882. * @abstract
  37883. * @return {Number} The maximum anisotropy texture filtering value.
  37884. */
  37885. getMaxAnisotropy() {}
  37886. /**
  37887. * Returns the drawing buffer size.
  37888. *
  37889. * @return {Vector2} The drawing buffer size.
  37890. */
  37891. getDrawingBufferSize() {
  37892. _vector2 = _vector2 || new Vector2();
  37893. return this.renderer.getDrawingBufferSize( _vector2 );
  37894. }
  37895. /**
  37896. * Defines the scissor test.
  37897. *
  37898. * @abstract
  37899. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  37900. */
  37901. setScissorTest( /*boolean*/ ) { }
  37902. /**
  37903. * Returns the clear color and alpha into a single
  37904. * color object.
  37905. *
  37906. * @return {Color4} The clear color.
  37907. */
  37908. getClearColor() {
  37909. const renderer = this.renderer;
  37910. _color4 = _color4 || new Color4();
  37911. renderer.getClearColor( _color4 );
  37912. _color4.getRGB( _color4, this.renderer.currentColorSpace );
  37913. return _color4;
  37914. }
  37915. /**
  37916. * Returns the DOM element. If no DOM element exists, the backend
  37917. * creates a new one.
  37918. *
  37919. * @return {HTMLCanvasElement} The DOM element.
  37920. */
  37921. getDomElement() {
  37922. let domElement = this.domElement;
  37923. if ( domElement === null ) {
  37924. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  37925. // OffscreenCanvas does not have setAttribute, see #22811
  37926. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  37927. this.domElement = domElement;
  37928. }
  37929. return domElement;
  37930. }
  37931. /**
  37932. * Sets a dictionary for the given object into the
  37933. * internal data structure.
  37934. *
  37935. * @param {Object} object - The object.
  37936. * @param {Object} value - The dictionary to set.
  37937. */
  37938. set( object, value ) {
  37939. this.data.set( object, value );
  37940. }
  37941. /**
  37942. * Returns the dictionary for the given object.
  37943. *
  37944. * @param {Object} object - The object.
  37945. * @return {Object} The object's dictionary.
  37946. */
  37947. get( object ) {
  37948. let map = this.data.get( object );
  37949. if ( map === undefined ) {
  37950. map = {};
  37951. this.data.set( object, map );
  37952. }
  37953. return map;
  37954. }
  37955. /**
  37956. * Checks if the given object has a dictionary
  37957. * with data defined.
  37958. *
  37959. * @param {Object} object - The object.
  37960. * @return {Boolean} Whether a dictionary for the given object as been defined or not.
  37961. */
  37962. has( object ) {
  37963. return this.data.has( object );
  37964. }
  37965. /**
  37966. * Deletes an object from the internal data structure.
  37967. *
  37968. * @param {Object} object - The object to delete.
  37969. */
  37970. delete( object ) {
  37971. this.data.delete( object );
  37972. }
  37973. /**
  37974. * Frees internal resources.
  37975. *
  37976. * @abstract
  37977. */
  37978. dispose() { }
  37979. }
  37980. let _id$1 = 0;
  37981. /**
  37982. * This module is internally used in context of compute shaders.
  37983. * This type of shader is not natively supported in WebGL 2 and
  37984. * thus implemented via Transform Feedback. `DualAttributeData`
  37985. * manages the related data.
  37986. *
  37987. * @private
  37988. */
  37989. class DualAttributeData {
  37990. constructor( attributeData, dualBuffer ) {
  37991. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  37992. this.type = attributeData.type;
  37993. this.bufferType = attributeData.bufferType;
  37994. this.pbo = attributeData.pbo;
  37995. this.byteLength = attributeData.byteLength;
  37996. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  37997. this.version = attributeData.version;
  37998. this.isInteger = attributeData.isInteger;
  37999. this.activeBufferIndex = 0;
  38000. this.baseId = attributeData.id;
  38001. }
  38002. get id() {
  38003. return `${ this.baseId }|${ this.activeBufferIndex }`;
  38004. }
  38005. get bufferGPU() {
  38006. return this.buffers[ this.activeBufferIndex ];
  38007. }
  38008. get transformBuffer() {
  38009. return this.buffers[ this.activeBufferIndex ^ 1 ];
  38010. }
  38011. switchBuffers() {
  38012. this.activeBufferIndex ^= 1;
  38013. }
  38014. }
  38015. /**
  38016. * A WebGL 2 backend utility module for managing shader attributes.
  38017. *
  38018. * @private
  38019. */
  38020. class WebGLAttributeUtils {
  38021. /**
  38022. * Constructs a new utility object.
  38023. *
  38024. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38025. */
  38026. constructor( backend ) {
  38027. /**
  38028. * A reference to the WebGL 2 backend.
  38029. *
  38030. * @type {WebGLBackend}
  38031. */
  38032. this.backend = backend;
  38033. }
  38034. /**
  38035. * Creates the GPU buffer for the given buffer attribute.
  38036. *
  38037. * @param {BufferAttribute} attribute - The buffer attribute.
  38038. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38039. */
  38040. createAttribute( attribute, bufferType ) {
  38041. const backend = this.backend;
  38042. const { gl } = backend;
  38043. const array = attribute.array;
  38044. const usage = attribute.usage || gl.STATIC_DRAW;
  38045. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38046. const bufferData = backend.get( bufferAttribute );
  38047. let bufferGPU = bufferData.bufferGPU;
  38048. if ( bufferGPU === undefined ) {
  38049. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  38050. bufferData.bufferGPU = bufferGPU;
  38051. bufferData.bufferType = bufferType;
  38052. bufferData.version = bufferAttribute.version;
  38053. }
  38054. //attribute.onUploadCallback();
  38055. let type;
  38056. if ( array instanceof Float32Array ) {
  38057. type = gl.FLOAT;
  38058. } else if ( array instanceof Uint16Array ) {
  38059. if ( attribute.isFloat16BufferAttribute ) {
  38060. type = gl.HALF_FLOAT;
  38061. } else {
  38062. type = gl.UNSIGNED_SHORT;
  38063. }
  38064. } else if ( array instanceof Int16Array ) {
  38065. type = gl.SHORT;
  38066. } else if ( array instanceof Uint32Array ) {
  38067. type = gl.UNSIGNED_INT;
  38068. } else if ( array instanceof Int32Array ) {
  38069. type = gl.INT;
  38070. } else if ( array instanceof Int8Array ) {
  38071. type = gl.BYTE;
  38072. } else if ( array instanceof Uint8Array ) {
  38073. type = gl.UNSIGNED_BYTE;
  38074. } else if ( array instanceof Uint8ClampedArray ) {
  38075. type = gl.UNSIGNED_BYTE;
  38076. } else {
  38077. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  38078. }
  38079. let attributeData = {
  38080. bufferGPU,
  38081. bufferType,
  38082. type,
  38083. byteLength: array.byteLength,
  38084. bytesPerElement: array.BYTES_PER_ELEMENT,
  38085. version: attribute.version,
  38086. pbo: attribute.pbo,
  38087. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  38088. id: _id$1 ++
  38089. };
  38090. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  38091. // create buffer for transform feedback use
  38092. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  38093. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  38094. }
  38095. backend.set( attribute, attributeData );
  38096. }
  38097. /**
  38098. * Updates the GPU buffer of the given buffer attribute.
  38099. *
  38100. * @param {BufferAttribute} attribute - The buffer attribute.
  38101. */
  38102. updateAttribute( attribute ) {
  38103. const backend = this.backend;
  38104. const { gl } = backend;
  38105. const array = attribute.array;
  38106. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38107. const bufferData = backend.get( bufferAttribute );
  38108. const bufferType = bufferData.bufferType;
  38109. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  38110. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  38111. if ( updateRanges.length === 0 ) {
  38112. // Not using update ranges
  38113. gl.bufferSubData( bufferType, 0, array );
  38114. } else {
  38115. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  38116. const range = updateRanges[ i ];
  38117. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  38118. array, range.start, range.count );
  38119. }
  38120. bufferAttribute.clearUpdateRanges();
  38121. }
  38122. gl.bindBuffer( bufferType, null );
  38123. bufferData.version = bufferAttribute.version;
  38124. }
  38125. /**
  38126. * Destroys the GPU buffer of the given buffer attribute.
  38127. *
  38128. * @param {BufferAttribute} attribute - The buffer attribute.
  38129. */
  38130. destroyAttribute( attribute ) {
  38131. const backend = this.backend;
  38132. const { gl } = backend;
  38133. if ( attribute.isInterleavedBufferAttribute ) {
  38134. backend.delete( attribute.data );
  38135. }
  38136. const attributeData = backend.get( attribute );
  38137. gl.deleteBuffer( attributeData.bufferGPU );
  38138. backend.delete( attribute );
  38139. }
  38140. /**
  38141. * This method performs a readback operation by moving buffer data from
  38142. * a storage buffer attribute from the GPU to the CPU.
  38143. *
  38144. * @async
  38145. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38146. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38147. */
  38148. async getArrayBufferAsync( attribute ) {
  38149. const backend = this.backend;
  38150. const { gl } = backend;
  38151. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  38152. const { bufferGPU } = backend.get( bufferAttribute );
  38153. const array = attribute.array;
  38154. const byteLength = array.byteLength;
  38155. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  38156. const writeBuffer = gl.createBuffer();
  38157. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38158. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  38159. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  38160. await backend.utils._clientWaitAsync();
  38161. const dstBuffer = new attribute.array.constructor( array.length );
  38162. // Ensure the buffer is bound before reading
  38163. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  38164. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  38165. gl.deleteBuffer( writeBuffer );
  38166. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  38167. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  38168. return dstBuffer.buffer;
  38169. }
  38170. /**
  38171. * Creates a WebGL buffer with the given data.
  38172. *
  38173. * @private
  38174. * @param {WebGL2RenderingContext} gl - The rendering context.
  38175. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  38176. * @param {TypedArray} array - The array of the buffer attribute.
  38177. * @param {GLenum} usage - The usage.
  38178. * @return {WebGLBuffer} The WebGL buffer.
  38179. */
  38180. _createBuffer( gl, bufferType, array, usage ) {
  38181. const bufferGPU = gl.createBuffer();
  38182. gl.bindBuffer( bufferType, bufferGPU );
  38183. gl.bufferData( bufferType, array, usage );
  38184. gl.bindBuffer( bufferType, null );
  38185. return bufferGPU;
  38186. }
  38187. }
  38188. let initialized$1 = false, equationToGL, factorToGL;
  38189. /**
  38190. * A WebGL 2 backend utility module for managing the WebGL state.
  38191. *
  38192. * The major goal of this module is to reduce the number of state changes
  38193. * by caching the WEbGL state with a series of variables. In this way, the
  38194. * renderer only executes state change commands when necessary which
  38195. * improves the overall performance.
  38196. *
  38197. * @private
  38198. */
  38199. class WebGLState {
  38200. /**
  38201. * Constructs a new utility object.
  38202. *
  38203. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38204. */
  38205. constructor( backend ) {
  38206. /**
  38207. * A reference to the WebGL 2 backend.
  38208. *
  38209. * @type {WebGLBackend}
  38210. */
  38211. this.backend = backend;
  38212. /**
  38213. * A reference to the rendering context.
  38214. *
  38215. * @type {WebGL2RenderingContext}
  38216. */
  38217. this.gl = this.backend.gl;
  38218. // Below properties are intended to cache
  38219. // the WebGL state and are not explicitly
  38220. // documented for convenience reasons.
  38221. this.enabled = {};
  38222. this.currentFlipSided = null;
  38223. this.currentCullFace = null;
  38224. this.currentProgram = null;
  38225. this.currentBlendingEnabled = false;
  38226. this.currentBlending = null;
  38227. this.currentBlendSrc = null;
  38228. this.currentBlendDst = null;
  38229. this.currentBlendSrcAlpha = null;
  38230. this.currentBlendDstAlpha = null;
  38231. this.currentPremultipledAlpha = null;
  38232. this.currentPolygonOffsetFactor = null;
  38233. this.currentPolygonOffsetUnits = null;
  38234. this.currentColorMask = null;
  38235. this.currentDepthFunc = null;
  38236. this.currentDepthMask = null;
  38237. this.currentStencilFunc = null;
  38238. this.currentStencilRef = null;
  38239. this.currentStencilFuncMask = null;
  38240. this.currentStencilFail = null;
  38241. this.currentStencilZFail = null;
  38242. this.currentStencilZPass = null;
  38243. this.currentStencilMask = null;
  38244. this.currentLineWidth = null;
  38245. this.currentClippingPlanes = 0;
  38246. this.currentBoundFramebuffers = {};
  38247. this.currentDrawbuffers = new WeakMap();
  38248. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  38249. this.currentTextureSlot = null;
  38250. this.currentBoundTextures = {};
  38251. this.currentBoundBufferBases = {};
  38252. if ( initialized$1 === false ) {
  38253. this._init();
  38254. initialized$1 = true;
  38255. }
  38256. }
  38257. /**
  38258. * Inits the state of the utility.
  38259. *
  38260. * @private
  38261. */
  38262. _init() {
  38263. const gl = this.gl;
  38264. // Store only WebGL constants here.
  38265. equationToGL = {
  38266. [ AddEquation ]: gl.FUNC_ADD,
  38267. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  38268. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  38269. };
  38270. factorToGL = {
  38271. [ ZeroFactor ]: gl.ZERO,
  38272. [ OneFactor ]: gl.ONE,
  38273. [ SrcColorFactor ]: gl.SRC_COLOR,
  38274. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  38275. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  38276. [ DstColorFactor ]: gl.DST_COLOR,
  38277. [ DstAlphaFactor ]: gl.DST_ALPHA,
  38278. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  38279. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  38280. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  38281. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  38282. };
  38283. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  38284. const viewportParam = gl.getParameter( gl.VIEWPORT );
  38285. this.currentScissor = new Vector4().fromArray( scissorParam );
  38286. this.currentViewport = new Vector4().fromArray( viewportParam );
  38287. this._tempVec4 = new Vector4();
  38288. }
  38289. /**
  38290. * Enables the given WebGL capability.
  38291. *
  38292. * This method caches the capability state so
  38293. * `gl.enable()` is only called when necessary.
  38294. *
  38295. * @param {GLenum} id - The capability to enable.
  38296. */
  38297. enable( id ) {
  38298. const { enabled } = this;
  38299. if ( enabled[ id ] !== true ) {
  38300. this.gl.enable( id );
  38301. enabled[ id ] = true;
  38302. }
  38303. }
  38304. /**
  38305. * Disables the given WebGL capability.
  38306. *
  38307. * This method caches the capability state so
  38308. * `gl.disable()` is only called when necessary.
  38309. *
  38310. * @param {GLenum} id - The capability to enable.
  38311. */
  38312. disable( id ) {
  38313. const { enabled } = this;
  38314. if ( enabled[ id ] !== false ) {
  38315. this.gl.disable( id );
  38316. enabled[ id ] = false;
  38317. }
  38318. }
  38319. /**
  38320. * Specifies whether polygons are front- or back-facing
  38321. * by setting the winding orientation.
  38322. *
  38323. * This method caches the state so `gl.frontFace()` is only
  38324. * called when necessary.
  38325. *
  38326. * @param {Boolean} flipSided - Whether triangles flipped their sides or not.
  38327. */
  38328. setFlipSided( flipSided ) {
  38329. if ( this.currentFlipSided !== flipSided ) {
  38330. const { gl } = this;
  38331. if ( flipSided ) {
  38332. gl.frontFace( gl.CW );
  38333. } else {
  38334. gl.frontFace( gl.CCW );
  38335. }
  38336. this.currentFlipSided = flipSided;
  38337. }
  38338. }
  38339. /**
  38340. * Specifies whether or not front- and/or back-facing
  38341. * polygons can be culled.
  38342. *
  38343. * This method caches the state so `gl.cullFace()` is only
  38344. * called when necessary.
  38345. *
  38346. * @param {Number} cullFace - Defines which polygons are candidates for culling.
  38347. */
  38348. setCullFace( cullFace ) {
  38349. const { gl } = this;
  38350. if ( cullFace !== CullFaceNone ) {
  38351. this.enable( gl.CULL_FACE );
  38352. if ( cullFace !== this.currentCullFace ) {
  38353. if ( cullFace === CullFaceBack ) {
  38354. gl.cullFace( gl.BACK );
  38355. } else if ( cullFace === CullFaceFront ) {
  38356. gl.cullFace( gl.FRONT );
  38357. } else {
  38358. gl.cullFace( gl.FRONT_AND_BACK );
  38359. }
  38360. }
  38361. } else {
  38362. this.disable( gl.CULL_FACE );
  38363. }
  38364. this.currentCullFace = cullFace;
  38365. }
  38366. /**
  38367. * Specifies the width of line primitives.
  38368. *
  38369. * This method caches the state so `gl.lineWidth()` is only
  38370. * called when necessary.
  38371. *
  38372. * @param {Number} width - The line width.
  38373. */
  38374. setLineWidth( width ) {
  38375. const { currentLineWidth, gl } = this;
  38376. if ( width !== currentLineWidth ) {
  38377. gl.lineWidth( width );
  38378. this.currentLineWidth = width;
  38379. }
  38380. }
  38381. /**
  38382. * Defines the blending.
  38383. *
  38384. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  38385. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  38386. *
  38387. * @param {Number} blending - The blending type.
  38388. * @param {Number} blendEquation - The blending equation.
  38389. * @param {Number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  38390. * @param {Number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  38391. * @param {Number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  38392. * @param {Number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  38393. * @param {Number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  38394. * @param {Boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  38395. */
  38396. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  38397. const { gl } = this;
  38398. if ( blending === NoBlending ) {
  38399. if ( this.currentBlendingEnabled === true ) {
  38400. this.disable( gl.BLEND );
  38401. this.currentBlendingEnabled = false;
  38402. }
  38403. return;
  38404. }
  38405. if ( this.currentBlendingEnabled === false ) {
  38406. this.enable( gl.BLEND );
  38407. this.currentBlendingEnabled = true;
  38408. }
  38409. if ( blending !== CustomBlending ) {
  38410. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  38411. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  38412. gl.blendEquation( gl.FUNC_ADD );
  38413. this.currentBlendEquation = AddEquation;
  38414. this.currentBlendEquationAlpha = AddEquation;
  38415. }
  38416. if ( premultipliedAlpha ) {
  38417. switch ( blending ) {
  38418. case NormalBlending:
  38419. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38420. break;
  38421. case AdditiveBlending:
  38422. gl.blendFunc( gl.ONE, gl.ONE );
  38423. break;
  38424. case SubtractiveBlending:
  38425. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38426. break;
  38427. case MultiplyBlending:
  38428. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  38429. break;
  38430. default:
  38431. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38432. break;
  38433. }
  38434. } else {
  38435. switch ( blending ) {
  38436. case NormalBlending:
  38437. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  38438. break;
  38439. case AdditiveBlending:
  38440. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  38441. break;
  38442. case SubtractiveBlending:
  38443. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  38444. break;
  38445. case MultiplyBlending:
  38446. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  38447. break;
  38448. default:
  38449. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  38450. break;
  38451. }
  38452. }
  38453. this.currentBlendSrc = null;
  38454. this.currentBlendDst = null;
  38455. this.currentBlendSrcAlpha = null;
  38456. this.currentBlendDstAlpha = null;
  38457. this.currentBlending = blending;
  38458. this.currentPremultipledAlpha = premultipliedAlpha;
  38459. }
  38460. return;
  38461. }
  38462. // custom blending
  38463. blendEquationAlpha = blendEquationAlpha || blendEquation;
  38464. blendSrcAlpha = blendSrcAlpha || blendSrc;
  38465. blendDstAlpha = blendDstAlpha || blendDst;
  38466. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  38467. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  38468. this.currentBlendEquation = blendEquation;
  38469. this.currentBlendEquationAlpha = blendEquationAlpha;
  38470. }
  38471. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  38472. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  38473. this.currentBlendSrc = blendSrc;
  38474. this.currentBlendDst = blendDst;
  38475. this.currentBlendSrcAlpha = blendSrcAlpha;
  38476. this.currentBlendDstAlpha = blendDstAlpha;
  38477. }
  38478. this.currentBlending = blending;
  38479. this.currentPremultipledAlpha = false;
  38480. }
  38481. /**
  38482. * Specifies whether colors can be written when rendering
  38483. * into a framebuffer or not.
  38484. *
  38485. * This method caches the state so `gl.colorMask()` is only
  38486. * called when necessary.
  38487. *
  38488. * @param {Boolean} colorMask - The color mask.
  38489. */
  38490. setColorMask( colorMask ) {
  38491. if ( this.currentColorMask !== colorMask ) {
  38492. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  38493. this.currentColorMask = colorMask;
  38494. }
  38495. }
  38496. /**
  38497. * Specifies whether the depth test is enabled or not.
  38498. *
  38499. * @param {Boolean} depthTest - Whether the depth test is enabled or not.
  38500. */
  38501. setDepthTest( depthTest ) {
  38502. const { gl } = this;
  38503. if ( depthTest ) {
  38504. this.enable( gl.DEPTH_TEST );
  38505. } else {
  38506. this.disable( gl.DEPTH_TEST );
  38507. }
  38508. }
  38509. /**
  38510. * Specifies whether depth values can be written when rendering
  38511. * into a framebuffer or not.
  38512. *
  38513. * This method caches the state so `gl.depthMask()` is only
  38514. * called when necessary.
  38515. *
  38516. * @param {Boolean} depthMask - The depth mask.
  38517. */
  38518. setDepthMask( depthMask ) {
  38519. if ( this.currentDepthMask !== depthMask ) {
  38520. this.gl.depthMask( depthMask );
  38521. this.currentDepthMask = depthMask;
  38522. }
  38523. }
  38524. /**
  38525. * Specifies the depth compare function.
  38526. *
  38527. * This method caches the state so `gl.depthFunc()` is only
  38528. * called when necessary.
  38529. *
  38530. * @param {Number} depthFunc - The depth compare function.
  38531. */
  38532. setDepthFunc( depthFunc ) {
  38533. if ( this.currentDepthFunc !== depthFunc ) {
  38534. const { gl } = this;
  38535. switch ( depthFunc ) {
  38536. case NeverDepth:
  38537. gl.depthFunc( gl.NEVER );
  38538. break;
  38539. case AlwaysDepth:
  38540. gl.depthFunc( gl.ALWAYS );
  38541. break;
  38542. case LessDepth:
  38543. gl.depthFunc( gl.LESS );
  38544. break;
  38545. case LessEqualDepth:
  38546. gl.depthFunc( gl.LEQUAL );
  38547. break;
  38548. case EqualDepth:
  38549. gl.depthFunc( gl.EQUAL );
  38550. break;
  38551. case GreaterEqualDepth:
  38552. gl.depthFunc( gl.GEQUAL );
  38553. break;
  38554. case GreaterDepth:
  38555. gl.depthFunc( gl.GREATER );
  38556. break;
  38557. case NotEqualDepth:
  38558. gl.depthFunc( gl.NOTEQUAL );
  38559. break;
  38560. default:
  38561. gl.depthFunc( gl.LEQUAL );
  38562. }
  38563. this.currentDepthFunc = depthFunc;
  38564. }
  38565. }
  38566. /**
  38567. * Specifies the viewport.
  38568. *
  38569. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38570. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  38571. * @param {Number} width - The width of the viewport.
  38572. * @param {Number} height - The height of the viewport.
  38573. *
  38574. */
  38575. scissor( x, y, width, height ) {
  38576. const scissor = this._tempVec4.set( x, y, width, height );
  38577. if ( this.currentScissor.equals( scissor ) === false ) {
  38578. const { gl } = this;
  38579. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  38580. this.currentScissor.copy( scissor );
  38581. }
  38582. }
  38583. /**
  38584. * Specifies the viewport.
  38585. *
  38586. * @param {Number} x - The x-coordinate of the lower left corner of the viewport.
  38587. * @param {Number} y - The y-coordinate of the lower left corner of the viewport.
  38588. * @param {Number} width - The width of the viewport.
  38589. * @param {Number} height - The height of the viewport.
  38590. *
  38591. */
  38592. viewport( x, y, width, height ) {
  38593. const viewport = this._tempVec4.set( x, y, width, height );
  38594. if ( this.currentViewport.equals( viewport ) === false ) {
  38595. const { gl } = this;
  38596. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  38597. this.currentViewport.copy( viewport );
  38598. }
  38599. }
  38600. /**
  38601. * Defines the scissor test.
  38602. *
  38603. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  38604. */
  38605. setScissorTest( boolean ) {
  38606. const gl = this.gl;
  38607. if ( boolean ) {
  38608. gl.enable( gl.SCISSOR_TEST );
  38609. } else {
  38610. gl.disable( gl.SCISSOR_TEST );
  38611. }
  38612. }
  38613. /**
  38614. * Specifies whether the stencil test is enabled or not.
  38615. *
  38616. * @param {Boolean} stencilTest - Whether the stencil test is enabled or not.
  38617. */
  38618. setStencilTest( stencilTest ) {
  38619. const { gl } = this;
  38620. if ( stencilTest ) {
  38621. this.enable( gl.STENCIL_TEST );
  38622. } else {
  38623. this.disable( gl.STENCIL_TEST );
  38624. }
  38625. }
  38626. /**
  38627. * Specifies whether stencil values can be written when rendering
  38628. * into a framebuffer or not.
  38629. *
  38630. * This method caches the state so `gl.stencilMask()` is only
  38631. * called when necessary.
  38632. *
  38633. * @param {Boolean} stencilMask - The stencil mask.
  38634. */
  38635. setStencilMask( stencilMask ) {
  38636. if ( this.currentStencilMask !== stencilMask ) {
  38637. this.gl.stencilMask( stencilMask );
  38638. this.currentStencilMask = stencilMask;
  38639. }
  38640. }
  38641. /**
  38642. * Specifies whether the stencil test functions.
  38643. *
  38644. * This method caches the state so `gl.stencilFunc()` is only
  38645. * called when necessary.
  38646. *
  38647. * @param {Number} stencilFunc - The stencil compare function.
  38648. * @param {Number} stencilRef - The reference value for the stencil test.
  38649. * @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.
  38650. */
  38651. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  38652. if ( this.currentStencilFunc !== stencilFunc ||
  38653. this.currentStencilRef !== stencilRef ||
  38654. this.currentStencilFuncMask !== stencilMask ) {
  38655. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  38656. this.currentStencilFunc = stencilFunc;
  38657. this.currentStencilRef = stencilRef;
  38658. this.currentStencilFuncMask = stencilMask;
  38659. }
  38660. }
  38661. /**
  38662. * Specifies whether the stencil test operation.
  38663. *
  38664. * This method caches the state so `gl.stencilOp()` is only
  38665. * called when necessary.
  38666. *
  38667. * @param {Number} stencilFail - The function to use when the stencil test fails.
  38668. * @param {Number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  38669. * @param {Number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  38670. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  38671. */
  38672. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  38673. if ( this.currentStencilFail !== stencilFail ||
  38674. this.currentStencilZFail !== stencilZFail ||
  38675. this.currentStencilZPass !== stencilZPass ) {
  38676. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  38677. this.currentStencilFail = stencilFail;
  38678. this.currentStencilZFail = stencilZFail;
  38679. this.currentStencilZPass = stencilZPass;
  38680. }
  38681. }
  38682. /**
  38683. * Configures the WebGL state for the given material.
  38684. *
  38685. * @param {Material} material - The material to configure the state for.
  38686. * @param {Number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  38687. * @param {Number} hardwareClippingPlanes - The number of hardware clipping planes.
  38688. */
  38689. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  38690. const { gl } = this;
  38691. material.side === DoubleSide
  38692. ? this.disable( gl.CULL_FACE )
  38693. : this.enable( gl.CULL_FACE );
  38694. let flipSided = ( material.side === BackSide );
  38695. if ( frontFaceCW ) flipSided = ! flipSided;
  38696. this.setFlipSided( flipSided );
  38697. ( material.blending === NormalBlending && material.transparent === false )
  38698. ? this.setBlending( NoBlending )
  38699. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  38700. this.setDepthFunc( material.depthFunc );
  38701. this.setDepthTest( material.depthTest );
  38702. this.setDepthMask( material.depthWrite );
  38703. this.setColorMask( material.colorWrite );
  38704. const stencilWrite = material.stencilWrite;
  38705. this.setStencilTest( stencilWrite );
  38706. if ( stencilWrite ) {
  38707. this.setStencilMask( material.stencilWriteMask );
  38708. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  38709. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  38710. }
  38711. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  38712. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  38713. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  38714. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  38715. if ( hardwareClippingPlanes > 0 ) {
  38716. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  38717. const CLIP_DISTANCE0_WEBGL = 0x3000;
  38718. for ( let i = 0; i < 8; i ++ ) {
  38719. if ( i < hardwareClippingPlanes ) {
  38720. this.enable( CLIP_DISTANCE0_WEBGL + i );
  38721. } else {
  38722. this.disable( CLIP_DISTANCE0_WEBGL + i );
  38723. }
  38724. }
  38725. }
  38726. }
  38727. }
  38728. /**
  38729. * Specifies the polygon offset.
  38730. *
  38731. * This method caches the state so `gl.polygonOffset()` is only
  38732. * called when necessary.
  38733. *
  38734. * @param {Boolean} polygonOffset - Whether polygon offset is enabled or not.
  38735. * @param {Number} factor - The scale factor for the variable depth offset for each polygon.
  38736. * @param {Number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  38737. */
  38738. setPolygonOffset( polygonOffset, factor, units ) {
  38739. const { gl } = this;
  38740. if ( polygonOffset ) {
  38741. this.enable( gl.POLYGON_OFFSET_FILL );
  38742. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  38743. gl.polygonOffset( factor, units );
  38744. this.currentPolygonOffsetFactor = factor;
  38745. this.currentPolygonOffsetUnits = units;
  38746. }
  38747. } else {
  38748. this.disable( gl.POLYGON_OFFSET_FILL );
  38749. }
  38750. }
  38751. /**
  38752. * Defines the usage of the given WebGL program.
  38753. *
  38754. * This method caches the state so `gl.useProgram()` is only
  38755. * called when necessary.
  38756. *
  38757. * @param {WebGLProgram} program - The WebGL program to use.
  38758. * @return {Boolean} Whether a program change has been executed or not.
  38759. */
  38760. useProgram( program ) {
  38761. if ( this.currentProgram !== program ) {
  38762. this.gl.useProgram( program );
  38763. this.currentProgram = program;
  38764. return true;
  38765. }
  38766. return false;
  38767. }
  38768. // framebuffer
  38769. /**
  38770. * Binds the given framebuffer.
  38771. *
  38772. * This method caches the state so `gl.bindFramebuffer()` is only
  38773. * called when necessary.
  38774. *
  38775. * @param {Number} target - The binding point (target).
  38776. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  38777. * @return {Boolean} Whether a bind has been executed or not.
  38778. */
  38779. bindFramebuffer( target, framebuffer ) {
  38780. const { gl, currentBoundFramebuffers } = this;
  38781. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  38782. gl.bindFramebuffer( target, framebuffer );
  38783. currentBoundFramebuffers[ target ] = framebuffer;
  38784. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  38785. if ( target === gl.DRAW_FRAMEBUFFER ) {
  38786. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  38787. }
  38788. if ( target === gl.FRAMEBUFFER ) {
  38789. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  38790. }
  38791. return true;
  38792. }
  38793. return false;
  38794. }
  38795. /**
  38796. * Defines draw buffers to which fragment colors are written into.
  38797. * Configures the MRT setup of custom framebuffers.
  38798. *
  38799. * This method caches the state so `gl.drawBuffers()` is only
  38800. * called when necessary.
  38801. *
  38802. * @param {RenderContext} renderContext - The render context.
  38803. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  38804. */
  38805. drawBuffers( renderContext, framebuffer ) {
  38806. const { gl } = this;
  38807. let drawBuffers = [];
  38808. let needsUpdate = false;
  38809. if ( renderContext.textures !== null ) {
  38810. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  38811. if ( drawBuffers === undefined ) {
  38812. drawBuffers = [];
  38813. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  38814. }
  38815. const textures = renderContext.textures;
  38816. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  38817. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  38818. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  38819. }
  38820. drawBuffers.length = textures.length;
  38821. needsUpdate = true;
  38822. }
  38823. } else {
  38824. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  38825. drawBuffers[ 0 ] = gl.BACK;
  38826. needsUpdate = true;
  38827. }
  38828. }
  38829. if ( needsUpdate ) {
  38830. gl.drawBuffers( drawBuffers );
  38831. }
  38832. }
  38833. // texture
  38834. /**
  38835. * Makes the given texture unit active.
  38836. *
  38837. * This method caches the state so `gl.activeTexture()` is only
  38838. * called when necessary.
  38839. *
  38840. * @param {Number} webglSlot - The texture unit to make active.
  38841. */
  38842. activeTexture( webglSlot ) {
  38843. const { gl, currentTextureSlot, maxTextures } = this;
  38844. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38845. if ( currentTextureSlot !== webglSlot ) {
  38846. gl.activeTexture( webglSlot );
  38847. this.currentTextureSlot = webglSlot;
  38848. }
  38849. }
  38850. /**
  38851. * Binds the given WebGL texture to a target.
  38852. *
  38853. * This method caches the state so `gl.bindTexture()` is only
  38854. * called when necessary.
  38855. *
  38856. * @param {Number} webglType - The binding point (target).
  38857. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  38858. * @param {Number} webglSlot - The texture.
  38859. */
  38860. bindTexture( webglType, webglTexture, webglSlot ) {
  38861. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  38862. if ( webglSlot === undefined ) {
  38863. if ( currentTextureSlot === null ) {
  38864. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  38865. } else {
  38866. webglSlot = currentTextureSlot;
  38867. }
  38868. }
  38869. let boundTexture = currentBoundTextures[ webglSlot ];
  38870. if ( boundTexture === undefined ) {
  38871. boundTexture = { type: undefined, texture: undefined };
  38872. currentBoundTextures[ webglSlot ] = boundTexture;
  38873. }
  38874. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  38875. if ( currentTextureSlot !== webglSlot ) {
  38876. gl.activeTexture( webglSlot );
  38877. this.currentTextureSlot = webglSlot;
  38878. }
  38879. gl.bindTexture( webglType, webglTexture );
  38880. boundTexture.type = webglType;
  38881. boundTexture.texture = webglTexture;
  38882. }
  38883. }
  38884. /**
  38885. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  38886. *
  38887. * This method caches the state so `gl.bindBufferBase()` is only
  38888. * called when necessary.
  38889. *
  38890. * @param {Number} target - The target for the bind operation.
  38891. * @param {Number} index - The index of the target.
  38892. * @param {WebGLBuffer} buffer - The WebGL buffer.
  38893. * @return {Boolean} Whether a bind has been executed or not.
  38894. */
  38895. bindBufferBase( target, index, buffer ) {
  38896. const { gl } = this;
  38897. const key = `${target}-${index}`;
  38898. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  38899. gl.bindBufferBase( target, index, buffer );
  38900. this.currentBoundBufferBases[ key ] = buffer;
  38901. return true;
  38902. }
  38903. return false;
  38904. }
  38905. /**
  38906. * Unbinds the current bound texture.
  38907. *
  38908. * This method caches the state so `gl.bindTexture()` is only
  38909. * called when necessary.
  38910. */
  38911. unbindTexture() {
  38912. const { gl, currentTextureSlot, currentBoundTextures } = this;
  38913. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  38914. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  38915. gl.bindTexture( boundTexture.type, null );
  38916. boundTexture.type = undefined;
  38917. boundTexture.texture = undefined;
  38918. }
  38919. }
  38920. }
  38921. /**
  38922. * A WebGL 2 backend utility module with common helpers.
  38923. *
  38924. * @private
  38925. */
  38926. class WebGLUtils {
  38927. /**
  38928. * Constructs a new utility object.
  38929. *
  38930. * @param {WebGLBackend} backend - The WebGL 2 backend.
  38931. */
  38932. constructor( backend ) {
  38933. /**
  38934. * A reference to the WebGL 2 backend.
  38935. *
  38936. * @type {WebGLBackend}
  38937. */
  38938. this.backend = backend;
  38939. /**
  38940. * A reference to the rendering context.
  38941. *
  38942. * @type {WebGL2RenderingContext}
  38943. */
  38944. this.gl = this.backend.gl;
  38945. /**
  38946. * A reference to a backend module holding extension-related
  38947. * utility functions.
  38948. *
  38949. * @type {WebGLExtensions}
  38950. */
  38951. this.extensions = backend.extensions;
  38952. }
  38953. /**
  38954. * Converts the given three.js constant into a WebGL constant.
  38955. * The method currently supports the conversion of texture formats
  38956. * and types.
  38957. *
  38958. * @param {Number} p - The three.js constant.
  38959. * @param {String} [colorSpace=NoColorSpace] - The color space.
  38960. * @return {Number} The corresponding WebGL constant.
  38961. */
  38962. convert( p, colorSpace = NoColorSpace ) {
  38963. const { gl, extensions } = this;
  38964. let extension;
  38965. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  38966. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  38967. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  38968. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  38969. if ( p === ByteType ) return gl.BYTE;
  38970. if ( p === ShortType ) return gl.SHORT;
  38971. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  38972. if ( p === IntType ) return gl.INT;
  38973. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  38974. if ( p === FloatType ) return gl.FLOAT;
  38975. if ( p === HalfFloatType ) {
  38976. return gl.HALF_FLOAT;
  38977. }
  38978. if ( p === AlphaFormat ) return gl.ALPHA;
  38979. if ( p === RGBFormat ) return gl.RGB;
  38980. if ( p === RGBAFormat ) return gl.RGBA;
  38981. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  38982. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  38983. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  38984. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  38985. // WebGL2 formats.
  38986. if ( p === RedFormat ) return gl.RED;
  38987. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  38988. if ( p === RGFormat ) return gl.RG;
  38989. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  38990. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  38991. // S3TC
  38992. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  38993. if ( colorSpace === SRGBColorSpace ) {
  38994. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  38995. if ( extension !== null ) {
  38996. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  38997. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  38998. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  38999. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  39000. } else {
  39001. return null;
  39002. }
  39003. } else {
  39004. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  39005. if ( extension !== null ) {
  39006. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  39007. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39008. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39009. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39010. } else {
  39011. return null;
  39012. }
  39013. }
  39014. }
  39015. // PVRTC
  39016. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  39017. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  39018. if ( extension !== null ) {
  39019. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  39020. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  39021. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  39022. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  39023. } else {
  39024. return null;
  39025. }
  39026. }
  39027. // ETC
  39028. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  39029. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  39030. if ( extension !== null ) {
  39031. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  39032. if ( p === RGBA_ETC2_EAC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  39033. } else {
  39034. return null;
  39035. }
  39036. }
  39037. // ASTC
  39038. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  39039. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  39040. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  39041. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  39042. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  39043. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  39044. if ( extension !== null ) {
  39045. if ( p === RGBA_ASTC_4x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  39046. if ( p === RGBA_ASTC_5x4_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  39047. if ( p === RGBA_ASTC_5x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  39048. if ( p === RGBA_ASTC_6x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  39049. if ( p === RGBA_ASTC_6x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  39050. if ( p === RGBA_ASTC_8x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  39051. if ( p === RGBA_ASTC_8x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  39052. if ( p === RGBA_ASTC_8x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  39053. if ( p === RGBA_ASTC_10x5_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  39054. if ( p === RGBA_ASTC_10x6_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  39055. if ( p === RGBA_ASTC_10x8_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  39056. if ( p === RGBA_ASTC_10x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  39057. if ( p === RGBA_ASTC_12x10_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  39058. if ( p === RGBA_ASTC_12x12_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  39059. } else {
  39060. return null;
  39061. }
  39062. }
  39063. // BPTC
  39064. if ( p === RGBA_BPTC_Format ) {
  39065. extension = extensions.get( 'EXT_texture_compression_bptc' );
  39066. if ( extension !== null ) {
  39067. if ( p === RGBA_BPTC_Format ) return ( colorSpace === SRGBColorSpace ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  39068. } else {
  39069. return null;
  39070. }
  39071. }
  39072. // RGTC
  39073. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  39074. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  39075. if ( extension !== null ) {
  39076. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  39077. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  39078. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  39079. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  39080. } else {
  39081. return null;
  39082. }
  39083. }
  39084. //
  39085. if ( p === UnsignedInt248Type ) {
  39086. return gl.UNSIGNED_INT_24_8;
  39087. }
  39088. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  39089. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  39090. }
  39091. /**
  39092. * This method can be used to synchronize the CPU with the GPU by waiting until
  39093. * ongoing GPU commands have been completed.
  39094. *
  39095. * @private
  39096. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  39097. */
  39098. _clientWaitAsync() {
  39099. const { gl } = this;
  39100. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  39101. gl.flush();
  39102. return new Promise( ( resolve, reject ) => {
  39103. function test() {
  39104. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  39105. if ( res === gl.WAIT_FAILED ) {
  39106. gl.deleteSync( sync );
  39107. reject();
  39108. return;
  39109. }
  39110. if ( res === gl.TIMEOUT_EXPIRED ) {
  39111. requestAnimationFrame( test );
  39112. return;
  39113. }
  39114. gl.deleteSync( sync );
  39115. resolve();
  39116. }
  39117. test();
  39118. } );
  39119. }
  39120. }
  39121. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  39122. /**
  39123. * A WebGL 2 backend utility module for managing textures.
  39124. *
  39125. * @private
  39126. */
  39127. class WebGLTextureUtils {
  39128. /**
  39129. * Constructs a new utility object.
  39130. *
  39131. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39132. */
  39133. constructor( backend ) {
  39134. /**
  39135. * A reference to the WebGL 2 backend.
  39136. *
  39137. * @type {WebGLBackend}
  39138. */
  39139. this.backend = backend;
  39140. /**
  39141. * A reference to the rendering context.
  39142. *
  39143. * @type {WebGL2RenderingContext}
  39144. */
  39145. this.gl = backend.gl;
  39146. /**
  39147. * A reference to a backend module holding extension-related
  39148. * utility functions.
  39149. *
  39150. * @type {WebGLExtensions}
  39151. */
  39152. this.extensions = backend.extensions;
  39153. /**
  39154. * A dictionary for managing default textures. The key
  39155. * is the binding point (target), the value the WEbGL texture object.
  39156. *
  39157. * @type {Object<GLenum,WebGLTexture>}
  39158. */
  39159. this.defaultTextures = {};
  39160. if ( initialized === false ) {
  39161. this._init();
  39162. initialized = true;
  39163. }
  39164. }
  39165. /**
  39166. * Inits the state of the utility.
  39167. *
  39168. * @private
  39169. */
  39170. _init() {
  39171. const gl = this.gl;
  39172. // Store only WebGL constants here.
  39173. wrappingToGL = {
  39174. [ RepeatWrapping ]: gl.REPEAT,
  39175. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  39176. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  39177. };
  39178. filterToGL = {
  39179. [ NearestFilter ]: gl.NEAREST,
  39180. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  39181. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  39182. [ LinearFilter ]: gl.LINEAR,
  39183. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  39184. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  39185. };
  39186. compareToGL = {
  39187. [ NeverCompare ]: gl.NEVER,
  39188. [ AlwaysCompare ]: gl.ALWAYS,
  39189. [ LessCompare ]: gl.LESS,
  39190. [ LessEqualCompare ]: gl.LEQUAL,
  39191. [ EqualCompare ]: gl.EQUAL,
  39192. [ GreaterEqualCompare ]: gl.GEQUAL,
  39193. [ GreaterCompare ]: gl.GREATER,
  39194. [ NotEqualCompare ]: gl.NOTEQUAL
  39195. };
  39196. }
  39197. /**
  39198. * Returns the native texture type for the given texture.
  39199. *
  39200. * @param {Texture} texture - The texture.
  39201. * @return {GLenum} The native texture type.
  39202. */
  39203. getGLTextureType( texture ) {
  39204. const { gl } = this;
  39205. let glTextureType;
  39206. if ( texture.isCubeTexture === true ) {
  39207. glTextureType = gl.TEXTURE_CUBE_MAP;
  39208. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  39209. glTextureType = gl.TEXTURE_2D_ARRAY;
  39210. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  39211. glTextureType = gl.TEXTURE_3D;
  39212. } else {
  39213. glTextureType = gl.TEXTURE_2D;
  39214. }
  39215. return glTextureType;
  39216. }
  39217. /**
  39218. * Returns the native texture type for the given texture.
  39219. *
  39220. * @param {String?} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  39221. * @param {GLenum} glFormat - The WebGL format.
  39222. * @param {GLenum} glType - The WebGL type.
  39223. * @param {String} colorSpace - The texture's color space.
  39224. * @param {Boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  39225. * @return {GLenum} The internal format.
  39226. */
  39227. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  39228. const { gl, extensions } = this;
  39229. if ( internalFormatName !== null ) {
  39230. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  39231. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  39232. }
  39233. let internalFormat = glFormat;
  39234. if ( glFormat === gl.RED ) {
  39235. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  39236. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  39237. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  39238. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  39239. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39240. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39241. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39242. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39243. }
  39244. if ( glFormat === gl.RED_INTEGER ) {
  39245. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  39246. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  39247. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  39248. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  39249. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  39250. if ( glType === gl.INT ) internalFormat = gl.R32I;
  39251. }
  39252. if ( glFormat === gl.RG ) {
  39253. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  39254. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  39255. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  39256. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  39257. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39258. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39259. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39260. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39261. }
  39262. if ( glFormat === gl.RG_INTEGER ) {
  39263. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  39264. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  39265. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  39266. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  39267. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  39268. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  39269. }
  39270. if ( glFormat === gl.RGB ) {
  39271. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  39272. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  39273. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  39274. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  39275. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39276. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39277. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39278. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39279. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8 : gl.RGB8;
  39280. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  39281. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39282. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  39283. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  39284. }
  39285. if ( glFormat === gl.RGB_INTEGER ) {
  39286. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  39287. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  39288. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  39289. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  39290. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  39291. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  39292. }
  39293. if ( glFormat === gl.RGBA ) {
  39294. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  39295. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  39296. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  39297. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  39298. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39299. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39300. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39301. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39302. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( colorSpace === SRGBColorSpace && forceLinearTransfer === false ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  39303. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  39304. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  39305. }
  39306. if ( glFormat === gl.RGBA_INTEGER ) {
  39307. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  39308. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  39309. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  39310. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  39311. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  39312. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  39313. }
  39314. if ( glFormat === gl.DEPTH_COMPONENT ) {
  39315. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH24_STENCIL8;
  39316. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  39317. }
  39318. if ( glFormat === gl.DEPTH_STENCIL ) {
  39319. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  39320. }
  39321. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  39322. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  39323. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  39324. extensions.get( 'EXT_color_buffer_float' );
  39325. }
  39326. return internalFormat;
  39327. }
  39328. /**
  39329. * Sets the texture parameters for the given texture.
  39330. *
  39331. * @param {GLenum} textureType - The texture type.
  39332. * @param {Texture} texture - The texture.
  39333. */
  39334. setTextureParameters( textureType, texture ) {
  39335. const { gl, extensions, backend } = this;
  39336. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  39337. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  39338. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  39339. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE );
  39340. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  39341. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  39342. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  39343. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  39344. }
  39345. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  39346. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  39347. // follow WebGPU backend mapping for texture filtering
  39348. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  39349. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  39350. if ( texture.compareFunction ) {
  39351. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  39352. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  39353. }
  39354. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39355. if ( texture.magFilter === NearestFilter ) return;
  39356. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  39357. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  39358. if ( texture.anisotropy > 1 ) {
  39359. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39360. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  39361. }
  39362. }
  39363. }
  39364. /**
  39365. * Creates a default texture for the given texture that can be used
  39366. * as a placeholder until the actual texture is ready for usage.
  39367. *
  39368. * @param {Texture} texture - The texture to create a default texture for.
  39369. */
  39370. createDefaultTexture( texture ) {
  39371. const { gl, backend, defaultTextures } = this;
  39372. const glTextureType = this.getGLTextureType( texture );
  39373. let textureGPU = defaultTextures[ glTextureType ];
  39374. if ( textureGPU === undefined ) {
  39375. textureGPU = gl.createTexture();
  39376. backend.state.bindTexture( glTextureType, textureGPU );
  39377. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  39378. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  39379. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  39380. defaultTextures[ glTextureType ] = textureGPU;
  39381. }
  39382. backend.set( texture, {
  39383. textureGPU,
  39384. glTextureType,
  39385. isDefault: true
  39386. } );
  39387. }
  39388. /**
  39389. * Defines a texture on the GPU for the given texture object.
  39390. *
  39391. * @param {Texture} texture - The texture.
  39392. * @param {Object} [options={}] - Optional configuration parameter.
  39393. * @return {undefined}
  39394. */
  39395. createTexture( texture, options ) {
  39396. const { gl, backend } = this;
  39397. const { levels, width, height, depth } = options;
  39398. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  39399. const glType = backend.utils.convert( texture.type );
  39400. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  39401. const textureGPU = gl.createTexture();
  39402. const glTextureType = this.getGLTextureType( texture );
  39403. backend.state.bindTexture( glTextureType, textureGPU );
  39404. this.setTextureParameters( glTextureType, texture );
  39405. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  39406. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  39407. } else if ( texture.isData3DTexture ) {
  39408. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  39409. } else if ( ! texture.isVideoTexture ) {
  39410. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  39411. }
  39412. backend.set( texture, {
  39413. textureGPU,
  39414. glTextureType,
  39415. glFormat,
  39416. glType,
  39417. glInternalFormat
  39418. } );
  39419. }
  39420. /**
  39421. * Uploads texture buffer data to the GPU memory.
  39422. *
  39423. * @param {WebGLBuffer} buffer - The buffer data.
  39424. * @param {Texture} texture - The texture,
  39425. */
  39426. copyBufferToTexture( buffer, texture ) {
  39427. const { gl, backend } = this;
  39428. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  39429. const { width, height } = texture.source.data;
  39430. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  39431. backend.state.bindTexture( glTextureType, textureGPU );
  39432. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  39433. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  39434. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  39435. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  39436. backend.state.unbindTexture();
  39437. // debug
  39438. // const framebuffer = gl.createFramebuffer();
  39439. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  39440. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  39441. // const readout = new Float32Array( width * height * 4 );
  39442. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  39443. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  39444. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  39445. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  39446. // console.log( readout );
  39447. }
  39448. /**
  39449. * Uploads the updated texture data to the GPU.
  39450. *
  39451. * @param {Texture} texture - The texture.
  39452. * @param {Object} [options={}] - Optional configuration parameter.
  39453. */
  39454. updateTexture( texture, options ) {
  39455. const { gl } = this;
  39456. const { width, height } = options;
  39457. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  39458. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  39459. return;
  39460. const getImage = ( source ) => {
  39461. if ( source.isDataTexture ) {
  39462. return source.image.data;
  39463. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  39464. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  39465. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  39466. source instanceof OffscreenCanvas ) {
  39467. return source;
  39468. }
  39469. return source.data;
  39470. };
  39471. this.backend.state.bindTexture( glTextureType, textureGPU );
  39472. this.setTextureParameters( glTextureType, texture );
  39473. if ( texture.isCompressedTexture ) {
  39474. const mipmaps = texture.mipmaps;
  39475. const image = options.image;
  39476. for ( let i = 0; i < mipmaps.length; i ++ ) {
  39477. const mipmap = mipmaps[ i ];
  39478. if ( texture.isCompressedArrayTexture ) {
  39479. if ( texture.format !== gl.RGBA ) {
  39480. if ( glFormat !== null ) {
  39481. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  39482. } else {
  39483. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  39484. }
  39485. } else {
  39486. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  39487. }
  39488. } else {
  39489. if ( glFormat !== null ) {
  39490. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  39491. } else {
  39492. console.warn( 'Unsupported compressed texture format' );
  39493. }
  39494. }
  39495. }
  39496. } else if ( texture.isCubeTexture ) {
  39497. const images = options.images;
  39498. for ( let i = 0; i < 6; i ++ ) {
  39499. const image = getImage( images[ i ] );
  39500. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  39501. }
  39502. } else if ( texture.isDataArrayTexture ) {
  39503. const image = options.image;
  39504. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39505. } else if ( texture.isData3DTexture ) {
  39506. const image = options.image;
  39507. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  39508. } else if ( texture.isVideoTexture ) {
  39509. texture.update();
  39510. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  39511. } else {
  39512. const image = getImage( options.image );
  39513. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  39514. }
  39515. }
  39516. /**
  39517. * Generates mipmaps for the given texture.
  39518. *
  39519. * @param {Texture} texture - The texture.
  39520. */
  39521. generateMipmaps( texture ) {
  39522. const { gl, backend } = this;
  39523. const { textureGPU, glTextureType } = backend.get( texture );
  39524. backend.state.bindTexture( glTextureType, textureGPU );
  39525. gl.generateMipmap( glTextureType );
  39526. }
  39527. /**
  39528. * Deallocates the render buffers of the given render target.
  39529. *
  39530. * @param {RenderTarget} renderTarget - The render target.
  39531. */
  39532. deallocateRenderBuffers( renderTarget ) {
  39533. const { gl, backend } = this;
  39534. // remove framebuffer reference
  39535. if ( renderTarget ) {
  39536. const renderContextData = backend.get( renderTarget );
  39537. renderContextData.renderBufferStorageSetup = undefined;
  39538. if ( renderContextData.framebuffers ) {
  39539. for ( const cacheKey in renderContextData.framebuffers ) {
  39540. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  39541. }
  39542. delete renderContextData.framebuffers;
  39543. }
  39544. if ( renderContextData.depthRenderbuffer ) {
  39545. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  39546. delete renderContextData.depthRenderbuffer;
  39547. }
  39548. if ( renderContextData.stencilRenderbuffer ) {
  39549. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  39550. delete renderContextData.stencilRenderbuffer;
  39551. }
  39552. if ( renderContextData.msaaFrameBuffer ) {
  39553. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  39554. delete renderContextData.msaaFrameBuffer;
  39555. }
  39556. if ( renderContextData.msaaRenderbuffers ) {
  39557. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  39558. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  39559. }
  39560. delete renderContextData.msaaRenderbuffers;
  39561. }
  39562. }
  39563. }
  39564. /**
  39565. * Destroys the GPU data for the given texture object.
  39566. *
  39567. * @param {Texture} texture - The texture.
  39568. */
  39569. destroyTexture( texture ) {
  39570. const { gl, backend } = this;
  39571. const { textureGPU, renderTarget } = backend.get( texture );
  39572. this.deallocateRenderBuffers( renderTarget );
  39573. gl.deleteTexture( textureGPU );
  39574. backend.delete( texture );
  39575. }
  39576. /**
  39577. * Copies data of the given source texture to the given destination texture.
  39578. *
  39579. * @param {Texture} srcTexture - The source texture.
  39580. * @param {Texture} dstTexture - The destination texture.
  39581. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  39582. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  39583. * @param {Number} [level=0] - The mip level to copy.
  39584. */
  39585. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  39586. const { gl, backend } = this;
  39587. const { state } = this.backend;
  39588. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  39589. let width, height, minX, minY;
  39590. let dstX, dstY;
  39591. if ( srcRegion !== null ) {
  39592. width = srcRegion.max.x - srcRegion.min.x;
  39593. height = srcRegion.max.y - srcRegion.min.y;
  39594. minX = srcRegion.min.x;
  39595. minY = srcRegion.min.y;
  39596. } else {
  39597. width = srcTexture.image.width;
  39598. height = srcTexture.image.height;
  39599. minX = 0;
  39600. minY = 0;
  39601. }
  39602. if ( dstPosition !== null ) {
  39603. dstX = dstPosition.x;
  39604. dstY = dstPosition.y;
  39605. } else {
  39606. dstX = 0;
  39607. dstY = 0;
  39608. }
  39609. state.bindTexture( glTextureType, dstTextureGPU );
  39610. // As another texture upload may have changed pixelStorei
  39611. // parameters, make sure they are correct for the dstTexture
  39612. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39613. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  39614. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  39615. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  39616. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  39617. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  39618. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  39619. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  39620. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  39621. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ level ] : srcTexture.image;
  39622. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  39623. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  39624. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  39625. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  39626. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  39627. const srcTextureData = backend.get( srcTexture );
  39628. const dstTextureData = backend.get( dstTexture );
  39629. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  39630. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  39631. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  39632. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  39633. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  39634. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  39635. let mask = gl.COLOR_BUFFER_BIT;
  39636. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  39637. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  39638. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  39639. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  39640. } else {
  39641. if ( srcTexture.isDataTexture ) {
  39642. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image.data );
  39643. } else {
  39644. if ( srcTexture.isCompressedTexture ) {
  39645. gl.compressedTexSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, image.width, image.height, glFormat, image.data );
  39646. } else {
  39647. gl.texSubImage2D( gl.TEXTURE_2D, level, dstX, dstY, width, height, glFormat, glType, image );
  39648. }
  39649. }
  39650. }
  39651. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  39652. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  39653. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  39654. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  39655. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  39656. // Generate mipmaps only when copying level 0
  39657. if ( level === 0 && dstTexture.generateMipmaps ) gl.generateMipmap( gl.TEXTURE_2D );
  39658. state.unbindTexture();
  39659. }
  39660. /**
  39661. * Copies the current bound framebuffer to the given texture.
  39662. *
  39663. * @param {Texture} texture - The destination texture.
  39664. * @param {RenderContext} renderContext - The render context.
  39665. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  39666. */
  39667. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  39668. const { gl } = this;
  39669. const { state } = this.backend;
  39670. const { textureGPU } = this.backend.get( texture );
  39671. const { x, y, z: width, w: height } = rectangle;
  39672. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  39673. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  39674. if ( requireDrawFrameBuffer ) {
  39675. const partial = ( x !== 0 || y !== 0 );
  39676. let mask;
  39677. let attachment;
  39678. if ( texture.isDepthTexture === true ) {
  39679. mask = gl.DEPTH_BUFFER_BIT;
  39680. attachment = gl.DEPTH_ATTACHMENT;
  39681. if ( renderContext.stencil ) {
  39682. mask |= gl.STENCIL_BUFFER_BIT;
  39683. }
  39684. } else {
  39685. mask = gl.COLOR_BUFFER_BIT;
  39686. attachment = gl.COLOR_ATTACHMENT0;
  39687. }
  39688. if ( partial ) {
  39689. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  39690. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  39691. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  39692. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39693. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  39694. const flippedY = srcHeight - y - height;
  39695. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  39696. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  39697. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39698. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  39699. state.unbindTexture();
  39700. } else {
  39701. const fb = gl.createFramebuffer();
  39702. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  39703. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  39704. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  39705. gl.deleteFramebuffer( fb );
  39706. }
  39707. } else {
  39708. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  39709. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  39710. state.unbindTexture();
  39711. }
  39712. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  39713. this.backend._setFramebuffer( renderContext );
  39714. }
  39715. /**
  39716. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  39717. *
  39718. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  39719. * @param {RenderContext} renderContext - The render context.
  39720. */
  39721. setupRenderBufferStorage( renderbuffer, renderContext ) {
  39722. const { gl } = this;
  39723. const renderTarget = renderContext.renderTarget;
  39724. const { samples, depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  39725. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  39726. if ( depthBuffer && ! stencilBuffer ) {
  39727. let glInternalFormat = gl.DEPTH_COMPONENT24;
  39728. if ( samples > 0 ) {
  39729. if ( depthTexture && depthTexture.isDepthTexture ) {
  39730. if ( depthTexture.type === gl.FLOAT ) {
  39731. glInternalFormat = gl.DEPTH_COMPONENT32F;
  39732. }
  39733. }
  39734. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  39735. } else {
  39736. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  39737. }
  39738. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39739. } else if ( depthBuffer && stencilBuffer ) {
  39740. if ( samples > 0 ) {
  39741. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  39742. } else {
  39743. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  39744. }
  39745. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  39746. }
  39747. }
  39748. /**
  39749. * Returns texture data as a typed array.
  39750. *
  39751. * @async
  39752. * @param {Texture} texture - The texture to copy.
  39753. * @param {Number} x - The x coordinate of the copy origin.
  39754. * @param {Number} y - The y coordinate of the copy origin.
  39755. * @param {Number} width - The width of the copy.
  39756. * @param {Number} height - The height of the copy.
  39757. * @param {Number} faceIndex - The face index.
  39758. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  39759. */
  39760. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  39761. const { backend, gl } = this;
  39762. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  39763. const fb = gl.createFramebuffer();
  39764. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  39765. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  39766. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  39767. const typedArrayType = this._getTypedArrayType( glType );
  39768. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  39769. const elementCount = width * height;
  39770. const byteLength = elementCount * bytesPerTexel;
  39771. const buffer = gl.createBuffer();
  39772. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39773. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  39774. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  39775. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39776. await backend.utils._clientWaitAsync();
  39777. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  39778. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  39779. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  39780. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  39781. gl.deleteFramebuffer( fb );
  39782. return dstBuffer;
  39783. }
  39784. /**
  39785. * Returns the corresponding typed array type for the given WebGL data type.
  39786. *
  39787. * @private
  39788. * @param {GLenum} glType - The WebGL data type.
  39789. * @return {TypedArray.constructor} The typed array type.
  39790. */
  39791. _getTypedArrayType( glType ) {
  39792. const { gl } = this;
  39793. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  39794. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  39795. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  39796. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  39797. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  39798. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  39799. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  39800. if ( glType === gl.FLOAT ) return Float32Array;
  39801. throw new Error( `Unsupported WebGL type: ${glType}` );
  39802. }
  39803. /**
  39804. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  39805. *
  39806. * @private
  39807. * @param {GLenum} glType - The WebGL data type.
  39808. * @param {GLenum} glFormat - The WebGL texture format.
  39809. * @return {Number} The bytes-per-texel.
  39810. */
  39811. _getBytesPerTexel( glType, glFormat ) {
  39812. const { gl } = this;
  39813. let bytesPerComponent = 0;
  39814. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  39815. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  39816. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  39817. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  39818. glType === gl.UNSIGNED_SHORT ||
  39819. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  39820. if ( glType === gl.UNSIGNED_INT ||
  39821. glType === gl.FLOAT ) bytesPerComponent = 4;
  39822. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  39823. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  39824. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  39825. }
  39826. }
  39827. /**
  39828. * A WebGL 2 backend utility module for managing extensions.
  39829. *
  39830. * @private
  39831. */
  39832. class WebGLExtensions {
  39833. /**
  39834. * Constructs a new utility object.
  39835. *
  39836. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39837. */
  39838. constructor( backend ) {
  39839. /**
  39840. * A reference to the WebGL 2 backend.
  39841. *
  39842. * @type {WebGLBackend}
  39843. */
  39844. this.backend = backend;
  39845. /**
  39846. * A reference to the rendering context.
  39847. *
  39848. * @type {WebGL2RenderingContext}
  39849. */
  39850. this.gl = this.backend.gl;
  39851. /**
  39852. * A list with all the supported WebGL extensions.
  39853. *
  39854. * @type {Array<String>}
  39855. */
  39856. this.availableExtensions = this.gl.getSupportedExtensions();
  39857. /**
  39858. * A dictionary with requested WebGL extensions.
  39859. * The key is the name of the extension, the value
  39860. * the requested extension object.
  39861. *
  39862. * @type {Object<String,Object>}
  39863. */
  39864. this.extensions = {};
  39865. }
  39866. /**
  39867. * Returns the extension object for the given extension name.
  39868. *
  39869. * @param {String} name - The extension name.
  39870. * @return {Object} The extension object.
  39871. */
  39872. get( name ) {
  39873. let extension = this.extensions[ name ];
  39874. if ( extension === undefined ) {
  39875. extension = this.gl.getExtension( name );
  39876. this.extensions[ name ] = extension;
  39877. }
  39878. return extension;
  39879. }
  39880. /**
  39881. * Returns `true` if the requested extension is available.
  39882. *
  39883. * @param {String} name - The extension name.
  39884. * @return {Boolean} Whether the given extension is available or not.
  39885. */
  39886. has( name ) {
  39887. return this.availableExtensions.includes( name );
  39888. }
  39889. }
  39890. /**
  39891. * A WebGL 2 backend utility module for managing the device's capabilities.
  39892. *
  39893. * @private
  39894. */
  39895. class WebGLCapabilities {
  39896. /**
  39897. * Constructs a new utility object.
  39898. *
  39899. * @param {WebGLBackend} backend - The WebGL 2 backend.
  39900. */
  39901. constructor( backend ) {
  39902. /**
  39903. * A reference to the WebGL 2 backend.
  39904. *
  39905. * @type {WebGLBackend}
  39906. */
  39907. this.backend = backend;
  39908. /**
  39909. * This value holds the cached max anisotropy value.
  39910. *
  39911. * @type {Number?}
  39912. * @default null
  39913. */
  39914. this.maxAnisotropy = null;
  39915. }
  39916. /**
  39917. * Returns the maximum anisotropy texture filtering value. This value
  39918. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  39919. * WebGL extension.
  39920. *
  39921. * @return {Number} The maximum anisotropy texture filtering value.
  39922. */
  39923. getMaxAnisotropy() {
  39924. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  39925. const gl = this.backend.gl;
  39926. const extensions = this.backend.extensions;
  39927. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  39928. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  39929. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  39930. } else {
  39931. this.maxAnisotropy = 0;
  39932. }
  39933. return this.maxAnisotropy;
  39934. }
  39935. }
  39936. const GLFeatureName = {
  39937. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  39938. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  39939. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  39940. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  39941. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  39942. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  39943. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  39944. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  39945. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  39946. };
  39947. class WebGLBufferRenderer {
  39948. constructor( backend ) {
  39949. this.gl = backend.gl;
  39950. this.extensions = backend.extensions;
  39951. this.info = backend.renderer.info;
  39952. this.mode = null;
  39953. this.index = 0;
  39954. this.type = null;
  39955. this.object = null;
  39956. }
  39957. render( start, count ) {
  39958. const { gl, mode, object, type, info, index } = this;
  39959. if ( index !== 0 ) {
  39960. gl.drawElements( mode, count, type, start );
  39961. } else {
  39962. gl.drawArrays( mode, start, count );
  39963. }
  39964. info.update( object, count, mode, 1 );
  39965. }
  39966. renderInstances( start, count, primcount ) {
  39967. const { gl, mode, type, index, object, info } = this;
  39968. if ( primcount === 0 ) return;
  39969. if ( index !== 0 ) {
  39970. gl.drawElementsInstanced( mode, count, type, start, primcount );
  39971. } else {
  39972. gl.drawArraysInstanced( mode, start, count, primcount );
  39973. }
  39974. info.update( object, count, mode, primcount );
  39975. }
  39976. renderMultiDraw( starts, counts, drawCount ) {
  39977. const { extensions, mode, object, info } = this;
  39978. if ( drawCount === 0 ) return;
  39979. const extension = extensions.get( 'WEBGL_multi_draw' );
  39980. if ( extension === null ) {
  39981. for ( let i = 0; i < drawCount; i ++ ) {
  39982. this.render( starts[ i ], counts[ i ] );
  39983. }
  39984. } else {
  39985. if ( this.index !== 0 ) {
  39986. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  39987. } else {
  39988. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  39989. }
  39990. let elementCount = 0;
  39991. for ( let i = 0; i < drawCount; i ++ ) {
  39992. elementCount += counts[ i ];
  39993. }
  39994. info.update( object, elementCount, mode, 1 );
  39995. }
  39996. }
  39997. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  39998. const { extensions, mode, object, info } = this;
  39999. if ( drawCount === 0 ) return;
  40000. const extension = extensions.get( 'WEBGL_multi_draw' );
  40001. if ( extension === null ) {
  40002. for ( let i = 0; i < drawCount; i ++ ) {
  40003. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  40004. }
  40005. } else {
  40006. if ( this.index !== 0 ) {
  40007. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  40008. } else {
  40009. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  40010. }
  40011. let elementCount = 0;
  40012. for ( let i = 0; i < drawCount; i ++ ) {
  40013. elementCount += counts[ i ] * primcount[ i ];
  40014. }
  40015. info.update( object, elementCount, mode, 1 );
  40016. }
  40017. }
  40018. //
  40019. }
  40020. /**
  40021. * A backend implementation targeting WebGL 2.
  40022. *
  40023. * @private
  40024. * @augments Backend
  40025. */
  40026. class WebGLBackend extends Backend {
  40027. /**
  40028. * Constructs a new WebGPU backend.
  40029. *
  40030. * @param {Object} parameters - The configuration parameter.
  40031. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  40032. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  40033. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  40034. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  40035. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  40036. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  40037. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  40038. * @param {WebGL2RenderingContext} [parameters.context=undefined] - A WebGL 2 rendering context.
  40039. */
  40040. constructor( parameters = {} ) {
  40041. super( parameters );
  40042. /**
  40043. * This flag can be used for type testing.
  40044. *
  40045. * @type {Boolean}
  40046. * @readonly
  40047. * @default true
  40048. */
  40049. this.isWebGLBackend = true;
  40050. /**
  40051. * A reference to a backend module holding shader attribute-related
  40052. * utility functions.
  40053. *
  40054. * @type {WebGLAttributeUtils?}
  40055. * @default null
  40056. */
  40057. this.attributeUtils = null;
  40058. /**
  40059. * A reference to a backend module holding extension-related
  40060. * utility functions.
  40061. *
  40062. * @type {WebGLExtensions?}
  40063. * @default null
  40064. */
  40065. this.extensions = null;
  40066. /**
  40067. * A reference to a backend module holding capability-related
  40068. * utility functions.
  40069. *
  40070. * @type {WebGLCapabilities?}
  40071. * @default null
  40072. */
  40073. this.capabilities = null;
  40074. /**
  40075. * A reference to a backend module holding texture-related
  40076. * utility functions.
  40077. *
  40078. * @type {WebGLTextureUtils?}
  40079. * @default null
  40080. */
  40081. this.textureUtils = null;
  40082. /**
  40083. * A reference to a backend module holding renderer-related
  40084. * utility functions.
  40085. *
  40086. * @type {WebGLBufferRenderer?}
  40087. * @default null
  40088. */
  40089. this.bufferRenderer = null;
  40090. /**
  40091. * A reference to the rendering context.
  40092. *
  40093. * @type {WebGL2RenderingContext?}
  40094. * @default null
  40095. */
  40096. this.gl = null;
  40097. /**
  40098. * A reference to a backend module holding state-related
  40099. * utility functions.
  40100. *
  40101. * @type {WebGLState?}
  40102. * @default null
  40103. */
  40104. this.state = null;
  40105. /**
  40106. * A reference to a backend module holding common
  40107. * utility functions.
  40108. *
  40109. * @type {WebGLUtils?}
  40110. * @default null
  40111. */
  40112. this.utils = null;
  40113. /**
  40114. * Dictionary for caching VAOs.
  40115. *
  40116. * @type {Object<String,WebGLVertexArrayObject>}
  40117. */
  40118. this.vaoCache = {};
  40119. /**
  40120. * Dictionary for caching transform feedback objects.
  40121. *
  40122. * @type {Object<String,WebGLTransformFeedback>}
  40123. */
  40124. this.transformFeedbackCache = {};
  40125. /**
  40126. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  40127. * Only relevant when using compute shaders.
  40128. *
  40129. * @type {Boolean}
  40130. * @default false
  40131. */
  40132. this.discard = false;
  40133. /**
  40134. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  40135. * device does not support the extension.
  40136. *
  40137. * @type {EXTDisjointTimerQueryWebGL2?}
  40138. * @default null
  40139. */
  40140. this.disjoint = null;
  40141. /**
  40142. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  40143. * device does not support the extension.
  40144. *
  40145. * @type {KHRParallelShaderCompile?}
  40146. * @default null
  40147. */
  40148. this.parallel = null;
  40149. /**
  40150. * Whether to track timestamps with a Timestamp Query API or not.
  40151. *
  40152. * @type {Boolean}
  40153. * @default false
  40154. */
  40155. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40156. /**
  40157. * A reference to the current render context.
  40158. *
  40159. * @private
  40160. * @type {RenderContext}
  40161. * @default null
  40162. */
  40163. this._currentContext = null;
  40164. /**
  40165. * A unique collection of bindings.
  40166. *
  40167. * @private
  40168. * @type {WeakSet}
  40169. */
  40170. this._knownBindings = new WeakSet();
  40171. /**
  40172. * The target framebuffer when rendering with
  40173. * the WebXR device API.
  40174. *
  40175. * @private
  40176. * @type {WebGLFramebuffer}
  40177. * @default null
  40178. */
  40179. this._xrFamebuffer = null;
  40180. }
  40181. /**
  40182. * Initializes the backend so it is ready for usage.
  40183. *
  40184. * @param {Renderer} renderer - The renderer.
  40185. */
  40186. init( renderer ) {
  40187. super.init( renderer );
  40188. //
  40189. const parameters = this.parameters;
  40190. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2' );
  40191. function onContextLost( event ) {
  40192. event.preventDefault();
  40193. const contextLossInfo = {
  40194. api: 'WebGL',
  40195. message: event.statusMessage || 'Unknown reason',
  40196. reason: null,
  40197. originalEvent: event
  40198. };
  40199. renderer.onDeviceLost( contextLossInfo );
  40200. }
  40201. this._onContextLost = onContextLost;
  40202. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  40203. this.gl = glContext;
  40204. this.extensions = new WebGLExtensions( this );
  40205. this.capabilities = new WebGLCapabilities( this );
  40206. this.attributeUtils = new WebGLAttributeUtils( this );
  40207. this.textureUtils = new WebGLTextureUtils( this );
  40208. this.bufferRenderer = new WebGLBufferRenderer( this );
  40209. this.state = new WebGLState( this );
  40210. this.utils = new WebGLUtils( this );
  40211. this.extensions.get( 'EXT_color_buffer_float' );
  40212. this.extensions.get( 'WEBGL_clip_cull_distance' );
  40213. this.extensions.get( 'OES_texture_float_linear' );
  40214. this.extensions.get( 'EXT_color_buffer_half_float' );
  40215. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  40216. this.extensions.get( 'WEBGL_render_shared_exponent' );
  40217. this.extensions.get( 'WEBGL_multi_draw' );
  40218. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  40219. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  40220. }
  40221. /**
  40222. * The coordinate system of the backend.
  40223. *
  40224. * @type {Number}
  40225. * @readonly
  40226. */
  40227. get coordinateSystem() {
  40228. return WebGLCoordinateSystem;
  40229. }
  40230. /**
  40231. * This method performs a readback operation by moving buffer data from
  40232. * a storage buffer attribute from the GPU to the CPU.
  40233. *
  40234. * @async
  40235. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40236. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40237. */
  40238. async getArrayBufferAsync( attribute ) {
  40239. return await this.attributeUtils.getArrayBufferAsync( attribute );
  40240. }
  40241. /**
  40242. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40243. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40244. *
  40245. * @async
  40246. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40247. */
  40248. async waitForGPU() {
  40249. await this.utils._clientWaitAsync();
  40250. }
  40251. /**
  40252. * Ensures the backend is XR compatible.
  40253. *
  40254. * @async
  40255. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  40256. */
  40257. async makeXRCompatible() {
  40258. const attributes = this.gl.getContextAttributes();
  40259. if ( attributes.xrCompatible !== true ) {
  40260. await this.gl.makeXRCompatible();
  40261. }
  40262. }
  40263. /**
  40264. * Sets the XR rendering destination.
  40265. *
  40266. * @param {WebGLFramebuffer} xrFamebuffer - The XR framebuffer.
  40267. */
  40268. setXRTarget( xrFamebuffer ) {
  40269. this._xrFamebuffer = xrFamebuffer;
  40270. }
  40271. /**
  40272. * Inits a time stamp query for the given render context.
  40273. *
  40274. * @param {RenderContext} renderContext - The render context.
  40275. */
  40276. initTimestampQuery( renderContext ) {
  40277. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40278. const renderContextData = this.get( renderContext );
  40279. if ( this.queryRunning ) {
  40280. if ( ! renderContextData.queryQueue ) renderContextData.queryQueue = [];
  40281. renderContextData.queryQueue.push( renderContext );
  40282. return;
  40283. }
  40284. if ( renderContextData.activeQuery ) {
  40285. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40286. renderContextData.activeQuery = null;
  40287. }
  40288. renderContextData.activeQuery = this.gl.createQuery();
  40289. if ( renderContextData.activeQuery !== null ) {
  40290. this.gl.beginQuery( this.disjoint.TIME_ELAPSED_EXT, renderContextData.activeQuery );
  40291. this.queryRunning = true;
  40292. }
  40293. }
  40294. // timestamp utils
  40295. /**
  40296. * Prepares the timestamp buffer.
  40297. *
  40298. * @param {RenderContext} renderContext - The render context.
  40299. */
  40300. prepareTimestampBuffer( renderContext ) {
  40301. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40302. const renderContextData = this.get( renderContext );
  40303. if ( renderContextData.activeQuery ) {
  40304. this.gl.endQuery( this.disjoint.TIME_ELAPSED_EXT );
  40305. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40306. renderContextData.gpuQueries.push( { query: renderContextData.activeQuery } );
  40307. renderContextData.activeQuery = null;
  40308. this.queryRunning = false;
  40309. if ( renderContextData.queryQueue && renderContextData.queryQueue.length > 0 ) {
  40310. const nextRenderContext = renderContextData.queryQueue.shift();
  40311. this.initTimestampQuery( nextRenderContext );
  40312. }
  40313. }
  40314. }
  40315. /**
  40316. * Resolves the time stamp for the given render context and type.
  40317. *
  40318. * @async
  40319. * @param {RenderContext} renderContext - The render context.
  40320. * @param {String} type - The render context.
  40321. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  40322. */
  40323. async resolveTimestampAsync( renderContext, type = 'render' ) {
  40324. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  40325. const renderContextData = this.get( renderContext );
  40326. if ( ! renderContextData.gpuQueries ) renderContextData.gpuQueries = [];
  40327. for ( let i = 0; i < renderContextData.gpuQueries.length; i ++ ) {
  40328. const queryInfo = renderContextData.gpuQueries[ i ];
  40329. const available = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT_AVAILABLE );
  40330. const disjoint = this.gl.getParameter( this.disjoint.GPU_DISJOINT_EXT );
  40331. if ( available && ! disjoint ) {
  40332. const elapsed = this.gl.getQueryParameter( queryInfo.query, this.gl.QUERY_RESULT );
  40333. const duration = Number( elapsed ) / 1000000; // Convert nanoseconds to milliseconds
  40334. this.gl.deleteQuery( queryInfo.query );
  40335. renderContextData.gpuQueries.splice( i, 1 ); // Remove the processed query
  40336. i --;
  40337. this.renderer.info.updateTimestamp( type, duration );
  40338. }
  40339. }
  40340. }
  40341. /**
  40342. * Returns the backend's rendering context.
  40343. *
  40344. * @return {WebGL2RenderingContext} The rendering context.
  40345. */
  40346. getContext() {
  40347. return this.gl;
  40348. }
  40349. /**
  40350. * This method is executed at the beginning of a render call and prepares
  40351. * the WebGL state for upcoming render calls
  40352. *
  40353. * @param {RenderContext} renderContext - The render context.
  40354. */
  40355. beginRender( renderContext ) {
  40356. const { state, gl } = this;
  40357. const renderContextData = this.get( renderContext );
  40358. //
  40359. //
  40360. this.initTimestampQuery( renderContext );
  40361. renderContextData.previousContext = this._currentContext;
  40362. this._currentContext = renderContext;
  40363. this._setFramebuffer( renderContext );
  40364. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  40365. //
  40366. if ( renderContext.viewport ) {
  40367. this.updateViewport( renderContext );
  40368. } else {
  40369. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40370. }
  40371. if ( renderContext.scissor ) {
  40372. const { x, y, width, height } = renderContext.scissorValue;
  40373. state.scissor( x, renderContext.height - height - y, width, height );
  40374. }
  40375. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40376. if ( occlusionQueryCount > 0 ) {
  40377. // Get a reference to the array of objects with queries. The renderContextData property
  40378. // can be changed by another render pass before the async reading of all previous queries complete
  40379. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  40380. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  40381. renderContextData.lastOcclusionObject = null;
  40382. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  40383. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  40384. renderContextData.occlusionQueryIndex = 0;
  40385. }
  40386. }
  40387. /**
  40388. * This method is executed at the end of a render call and finalizes work
  40389. * after draw calls.
  40390. *
  40391. * @param {RenderContext} renderContext - The render context.
  40392. */
  40393. finishRender( renderContext ) {
  40394. const { gl, state } = this;
  40395. const renderContextData = this.get( renderContext );
  40396. const previousContext = renderContextData.previousContext;
  40397. const occlusionQueryCount = renderContext.occlusionQueryCount;
  40398. if ( occlusionQueryCount > 0 ) {
  40399. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  40400. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40401. }
  40402. this.resolveOccludedAsync( renderContext );
  40403. }
  40404. const textures = renderContext.textures;
  40405. if ( textures !== null ) {
  40406. for ( let i = 0; i < textures.length; i ++ ) {
  40407. const texture = textures[ i ];
  40408. if ( texture.generateMipmaps ) {
  40409. this.generateMipmaps( texture );
  40410. }
  40411. }
  40412. }
  40413. this._currentContext = previousContext;
  40414. if ( renderContext.textures !== null && renderContext.renderTarget ) {
  40415. const renderTargetContextData = this.get( renderContext.renderTarget );
  40416. const { samples } = renderContext.renderTarget;
  40417. if ( samples > 0 ) {
  40418. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  40419. const mask = gl.COLOR_BUFFER_BIT;
  40420. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  40421. const textures = renderContext.textures;
  40422. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  40423. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  40424. for ( let i = 0; i < textures.length; i ++ ) {
  40425. // TODO Add support for MRT
  40426. if ( renderContext.scissor ) {
  40427. const { x, y, width, height } = renderContext.scissorValue;
  40428. const viewY = renderContext.height - height - y;
  40429. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  40430. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  40431. } else {
  40432. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  40433. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  40434. }
  40435. }
  40436. }
  40437. }
  40438. if ( previousContext !== null ) {
  40439. this._setFramebuffer( previousContext );
  40440. if ( previousContext.viewport ) {
  40441. this.updateViewport( previousContext );
  40442. } else {
  40443. state.viewport( 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight );
  40444. }
  40445. }
  40446. this.prepareTimestampBuffer( renderContext );
  40447. }
  40448. /**
  40449. * This method processes the result of occlusion queries and writes it
  40450. * into render context data.
  40451. *
  40452. * @async
  40453. * @param {RenderContext} renderContext - The render context.
  40454. */
  40455. resolveOccludedAsync( renderContext ) {
  40456. const renderContextData = this.get( renderContext );
  40457. // handle occlusion query results
  40458. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  40459. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  40460. const occluded = new WeakSet();
  40461. const { gl } = this;
  40462. renderContextData.currentOcclusionQueryObjects = null;
  40463. renderContextData.currentOcclusionQueries = null;
  40464. const check = () => {
  40465. let completed = 0;
  40466. // check all queries and requeue as appropriate
  40467. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  40468. const query = currentOcclusionQueries[ i ];
  40469. if ( query === null ) continue;
  40470. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  40471. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  40472. currentOcclusionQueries[ i ] = null;
  40473. gl.deleteQuery( query );
  40474. completed ++;
  40475. }
  40476. }
  40477. if ( completed < currentOcclusionQueries.length ) {
  40478. requestAnimationFrame( check );
  40479. } else {
  40480. renderContextData.occluded = occluded;
  40481. }
  40482. };
  40483. check();
  40484. }
  40485. }
  40486. /**
  40487. * Returns `true` if the given 3D object is fully occluded by other
  40488. * 3D objects in the scene.
  40489. *
  40490. * @param {RenderContext} renderContext - The render context.
  40491. * @param {Object3D} object - The 3D object to test.
  40492. * @return {Boolean} Whether the 3D object is fully occluded or not.
  40493. */
  40494. isOccluded( renderContext, object ) {
  40495. const renderContextData = this.get( renderContext );
  40496. return renderContextData.occluded && renderContextData.occluded.has( object );
  40497. }
  40498. /**
  40499. * Updates the viewport with the values from the given render context.
  40500. *
  40501. * @param {RenderContext} renderContext - The render context.
  40502. */
  40503. updateViewport( renderContext ) {
  40504. const { state } = this;
  40505. const { x, y, width, height } = renderContext.viewportValue;
  40506. state.viewport( x, renderContext.height - height - y, width, height );
  40507. }
  40508. /**
  40509. * Defines the scissor test.
  40510. *
  40511. * @param {Boolean} boolean - Whether the scissor test should be enabled or not.
  40512. */
  40513. setScissorTest( boolean ) {
  40514. const state = this.state;
  40515. state.setScissorTest( boolean );
  40516. }
  40517. /**
  40518. * Performs a clear operation.
  40519. *
  40520. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  40521. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  40522. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  40523. * @param {Object?} [descriptor=null] - The render context of the current set render target.
  40524. * @param {Boolean} [setFrameBuffer=true] - TODO.
  40525. */
  40526. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  40527. const { gl } = this;
  40528. if ( descriptor === null ) {
  40529. const clearColor = this.getClearColor();
  40530. // premultiply alpha
  40531. clearColor.r *= clearColor.a;
  40532. clearColor.g *= clearColor.a;
  40533. clearColor.b *= clearColor.a;
  40534. descriptor = {
  40535. textures: null,
  40536. clearColorValue: clearColor
  40537. };
  40538. }
  40539. //
  40540. let clear = 0;
  40541. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  40542. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  40543. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  40544. if ( clear !== 0 ) {
  40545. let clearColor;
  40546. if ( descriptor.clearColorValue ) {
  40547. clearColor = descriptor.clearColorValue;
  40548. } else {
  40549. clearColor = this.getClearColor();
  40550. // premultiply alpha
  40551. clearColor.r *= clearColor.a;
  40552. clearColor.g *= clearColor.a;
  40553. clearColor.b *= clearColor.a;
  40554. }
  40555. if ( depth ) this.state.setDepthMask( true );
  40556. if ( descriptor.textures === null ) {
  40557. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  40558. gl.clear( clear );
  40559. } else {
  40560. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  40561. if ( color ) {
  40562. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  40563. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  40564. }
  40565. }
  40566. if ( depth && stencil ) {
  40567. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, 1, 0 );
  40568. } else if ( depth ) {
  40569. gl.clearBufferfv( gl.DEPTH, 0, [ 1.0 ] );
  40570. } else if ( stencil ) {
  40571. gl.clearBufferiv( gl.STENCIL, 0, [ 0 ] );
  40572. }
  40573. }
  40574. }
  40575. }
  40576. /**
  40577. * This method is executed at the beginning of a compute call and
  40578. * prepares the state for upcoming compute tasks.
  40579. *
  40580. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40581. */
  40582. beginCompute( computeGroup ) {
  40583. const { state, gl } = this;
  40584. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  40585. this.initTimestampQuery( computeGroup );
  40586. }
  40587. /**
  40588. * Executes a compute command for the given compute node.
  40589. *
  40590. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  40591. * @param {Node} computeNode - The compute node.
  40592. * @param {Array<BindGroup>} bindings - The bindings.
  40593. * @param {ComputePipeline} pipeline - The compute pipeline.
  40594. */
  40595. compute( computeGroup, computeNode, bindings, pipeline ) {
  40596. const { state, gl } = this;
  40597. if ( this.discard === false ) {
  40598. // required here to handle async behaviour of render.compute()
  40599. gl.enable( gl.RASTERIZER_DISCARD );
  40600. this.discard = true;
  40601. }
  40602. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  40603. const vaoKey = this._getVaoKey( null, attributes );
  40604. const vaoGPU = this.vaoCache[ vaoKey ];
  40605. if ( vaoGPU === undefined ) {
  40606. this._createVao( null, attributes );
  40607. } else {
  40608. gl.bindVertexArray( vaoGPU );
  40609. }
  40610. state.useProgram( programGPU );
  40611. this._bindUniforms( bindings );
  40612. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  40613. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  40614. gl.beginTransformFeedback( gl.POINTS );
  40615. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  40616. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  40617. } else {
  40618. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  40619. }
  40620. gl.endTransformFeedback();
  40621. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  40622. // switch active buffers
  40623. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  40624. const dualAttributeData = transformBuffers[ i ];
  40625. if ( dualAttributeData.pbo ) {
  40626. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  40627. }
  40628. dualAttributeData.switchBuffers();
  40629. }
  40630. }
  40631. /**
  40632. * This method is executed at the end of a compute call and
  40633. * finalizes work after compute tasks.
  40634. *
  40635. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40636. */
  40637. finishCompute( computeGroup ) {
  40638. const gl = this.gl;
  40639. this.discard = false;
  40640. gl.disable( gl.RASTERIZER_DISCARD );
  40641. this.prepareTimestampBuffer( computeGroup );
  40642. if ( this._currentContext ) {
  40643. this._setFramebuffer( this._currentContext );
  40644. }
  40645. }
  40646. /**
  40647. * Executes a draw command for the given render object.
  40648. *
  40649. * @param {RenderObject} renderObject - The render object to draw.
  40650. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40651. */
  40652. draw( renderObject/*, info*/ ) {
  40653. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  40654. const { programGPU } = this.get( pipeline );
  40655. const { gl, state } = this;
  40656. const contextData = this.get( context );
  40657. const drawParams = renderObject.getDrawParameters();
  40658. if ( drawParams === null ) return;
  40659. //
  40660. this._bindUniforms( renderObject.getBindings() );
  40661. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  40662. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  40663. state.useProgram( programGPU );
  40664. //
  40665. const renderObjectData = this.get( renderObject );
  40666. let vaoGPU = renderObjectData.staticVao;
  40667. if ( vaoGPU === undefined || renderObjectData.geometryId !== renderObject.geometry.id ) {
  40668. const vaoKey = this._getVaoKey( renderObject.getIndex(), renderObject.getAttributes() );
  40669. vaoGPU = this.vaoCache[ vaoKey ];
  40670. if ( vaoGPU === undefined ) {
  40671. let staticVao;
  40672. ( { vaoGPU, staticVao } = this._createVao( renderObject.getIndex(), renderObject.getAttributes() ) );
  40673. if ( staticVao ) {
  40674. renderObjectData.staticVao = vaoGPU;
  40675. renderObjectData.geometryId = renderObject.geometry.id;
  40676. }
  40677. }
  40678. }
  40679. gl.bindVertexArray( vaoGPU );
  40680. //
  40681. const index = renderObject.getIndex();
  40682. //
  40683. const lastObject = contextData.lastOcclusionObject;
  40684. if ( lastObject !== object && lastObject !== undefined ) {
  40685. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  40686. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  40687. contextData.occlusionQueryIndex ++;
  40688. }
  40689. if ( object.occlusionTest === true ) {
  40690. const query = gl.createQuery();
  40691. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  40692. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  40693. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  40694. }
  40695. contextData.lastOcclusionObject = object;
  40696. }
  40697. //
  40698. const renderer = this.bufferRenderer;
  40699. if ( object.isPoints ) renderer.mode = gl.POINTS;
  40700. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  40701. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  40702. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  40703. else {
  40704. if ( material.wireframe === true ) {
  40705. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  40706. renderer.mode = gl.LINES;
  40707. } else {
  40708. renderer.mode = gl.TRIANGLES;
  40709. }
  40710. }
  40711. //
  40712. const { vertexCount, instanceCount } = drawParams;
  40713. let { firstVertex } = drawParams;
  40714. renderer.object = object;
  40715. if ( index !== null ) {
  40716. firstVertex *= index.array.BYTES_PER_ELEMENT;
  40717. const indexData = this.get( index );
  40718. renderer.index = index.count;
  40719. renderer.type = indexData.type;
  40720. } else {
  40721. renderer.index = 0;
  40722. }
  40723. const draw = () => {
  40724. if ( object.isBatchedMesh ) {
  40725. if ( object._multiDrawInstances !== null ) {
  40726. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  40727. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  40728. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  40729. } else {
  40730. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  40731. }
  40732. } else if ( instanceCount > 1 ) {
  40733. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  40734. } else {
  40735. renderer.render( firstVertex, vertexCount );
  40736. }
  40737. };
  40738. if ( renderObject.camera.isArrayCamera ) {
  40739. const cameraData = this.get( renderObject.camera );
  40740. const cameras = renderObject.camera.cameras;
  40741. if ( cameraData.indexesGPU === undefined ) {
  40742. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  40743. const indexesGPU = [];
  40744. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  40745. const bufferGPU = gl.createBuffer();
  40746. data[ 0 ] = i;
  40747. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  40748. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  40749. indexesGPU.push( bufferGPU );
  40750. }
  40751. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  40752. }
  40753. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  40754. const cameraIndexData = this.get( cameraIndex );
  40755. const pixelRatio = this.renderer.getPixelRatio();
  40756. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  40757. const subCamera = cameras[ i ];
  40758. if ( object.layers.test( subCamera.layers ) ) {
  40759. const vp = subCamera.viewport;
  40760. const x = vp.x * pixelRatio;
  40761. const y = vp.y * pixelRatio;
  40762. const width = vp.width * pixelRatio;
  40763. const height = vp.height * pixelRatio;
  40764. state.viewport(
  40765. Math.floor( x ),
  40766. Math.floor( renderObject.context.height - height - y ),
  40767. Math.floor( width ),
  40768. Math.floor( height )
  40769. );
  40770. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  40771. draw();
  40772. }
  40773. }
  40774. } else {
  40775. draw();
  40776. }
  40777. //
  40778. gl.bindVertexArray( null );
  40779. }
  40780. /**
  40781. * Explain why always null is returned.
  40782. *
  40783. * @param {RenderObject} renderObject - The render object.
  40784. * @return {Boolean} Whether the render pipeline requires an update or not.
  40785. */
  40786. needsRenderUpdate( /*renderObject*/ ) {
  40787. return false;
  40788. }
  40789. /**
  40790. * Explain why no cache key is computed.
  40791. *
  40792. * @param {RenderObject} renderObject - The render object.
  40793. * @return {String} The cache key.
  40794. */
  40795. getRenderCacheKey( /*renderObject*/ ) {
  40796. return '';
  40797. }
  40798. // textures
  40799. /**
  40800. * Creates a default texture for the given texture that can be used
  40801. * as a placeholder until the actual texture is ready for usage.
  40802. *
  40803. * @param {Texture} texture - The texture to create a default texture for.
  40804. */
  40805. createDefaultTexture( texture ) {
  40806. this.textureUtils.createDefaultTexture( texture );
  40807. }
  40808. /**
  40809. * Defines a texture on the GPU for the given texture object.
  40810. *
  40811. * @param {Texture} texture - The texture.
  40812. * @param {Object} [options={}] - Optional configuration parameter.
  40813. */
  40814. createTexture( texture, options ) {
  40815. this.textureUtils.createTexture( texture, options );
  40816. }
  40817. /**
  40818. * Uploads the updated texture data to the GPU.
  40819. *
  40820. * @param {Texture} texture - The texture.
  40821. * @param {Object} [options={}] - Optional configuration parameter.
  40822. */
  40823. updateTexture( texture, options ) {
  40824. this.textureUtils.updateTexture( texture, options );
  40825. }
  40826. /**
  40827. * Generates mipmaps for the given texture.
  40828. *
  40829. * @param {Texture} texture - The texture.
  40830. */
  40831. generateMipmaps( texture ) {
  40832. this.textureUtils.generateMipmaps( texture );
  40833. }
  40834. /**
  40835. * Destroys the GPU data for the given texture object.
  40836. *
  40837. * @param {Texture} texture - The texture.
  40838. */
  40839. destroyTexture( texture ) {
  40840. this.textureUtils.destroyTexture( texture );
  40841. }
  40842. /**
  40843. * Returns texture data as a typed array.
  40844. *
  40845. * @async
  40846. * @param {Texture} texture - The texture to copy.
  40847. * @param {Number} x - The x coordinate of the copy origin.
  40848. * @param {Number} y - The y coordinate of the copy origin.
  40849. * @param {Number} width - The width of the copy.
  40850. * @param {Number} height - The height of the copy.
  40851. * @param {Number} faceIndex - The face index.
  40852. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40853. */
  40854. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  40855. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  40856. }
  40857. /**
  40858. * This method does nothing since WebGL 2 has no concept of samplers.
  40859. *
  40860. * @param {Texture} texture - The texture to create the sampler for.
  40861. */
  40862. createSampler( /*texture*/ ) {
  40863. //console.warn( 'Abstract class.' );
  40864. }
  40865. /**
  40866. * This method does nothing since WebGL 2 has no concept of samplers.
  40867. *
  40868. * @param {Texture} texture - The texture to destroy the sampler for.
  40869. */
  40870. destroySampler( /*texture*/ ) {}
  40871. // node builder
  40872. /**
  40873. * Returns a node builder for the given render object.
  40874. *
  40875. * @param {RenderObject} object - The render object.
  40876. * @param {Renderer} renderer - The renderer.
  40877. * @return {GLSLNodeBuilder} The node builder.
  40878. */
  40879. createNodeBuilder( object, renderer ) {
  40880. return new GLSLNodeBuilder( object, renderer );
  40881. }
  40882. // program
  40883. /**
  40884. * Creates a shader program from the given programmable stage.
  40885. *
  40886. * @param {ProgrammableStage} program - The programmable stage.
  40887. */
  40888. createProgram( program ) {
  40889. const gl = this.gl;
  40890. const { stage, code } = program;
  40891. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  40892. gl.shaderSource( shader, code );
  40893. gl.compileShader( shader );
  40894. this.set( program, {
  40895. shaderGPU: shader
  40896. } );
  40897. }
  40898. /**
  40899. * Destroys the shader program of the given programmable stage.
  40900. *
  40901. * @param {ProgrammableStage} program - The programmable stage.
  40902. */
  40903. destroyProgram( program ) {
  40904. this.delete( program );
  40905. }
  40906. /**
  40907. * Creates a render pipeline for the given render object.
  40908. *
  40909. * @param {RenderObject} renderObject - The render object.
  40910. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  40911. */
  40912. createRenderPipeline( renderObject, promises ) {
  40913. const gl = this.gl;
  40914. const pipeline = renderObject.pipeline;
  40915. // Program
  40916. const { fragmentProgram, vertexProgram } = pipeline;
  40917. const programGPU = gl.createProgram();
  40918. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  40919. const vertexShader = this.get( vertexProgram ).shaderGPU;
  40920. gl.attachShader( programGPU, fragmentShader );
  40921. gl.attachShader( programGPU, vertexShader );
  40922. gl.linkProgram( programGPU );
  40923. this.set( pipeline, {
  40924. programGPU,
  40925. fragmentShader,
  40926. vertexShader
  40927. } );
  40928. if ( promises !== null && this.parallel ) {
  40929. const p = new Promise( ( resolve /*, reject*/ ) => {
  40930. const parallel = this.parallel;
  40931. const checkStatus = () => {
  40932. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  40933. this._completeCompile( renderObject, pipeline );
  40934. resolve();
  40935. } else {
  40936. requestAnimationFrame( checkStatus );
  40937. }
  40938. };
  40939. checkStatus();
  40940. } );
  40941. promises.push( p );
  40942. return;
  40943. }
  40944. this._completeCompile( renderObject, pipeline );
  40945. }
  40946. /**
  40947. * Formats the source code of error messages.
  40948. *
  40949. * @private
  40950. * @param {String} string - The code.
  40951. * @param {Number} errorLine - The error line.
  40952. * @return {String} The formatted code.
  40953. */
  40954. _handleSource( string, errorLine ) {
  40955. const lines = string.split( '\n' );
  40956. const lines2 = [];
  40957. const from = Math.max( errorLine - 6, 0 );
  40958. const to = Math.min( errorLine + 6, lines.length );
  40959. for ( let i = from; i < to; i ++ ) {
  40960. const line = i + 1;
  40961. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  40962. }
  40963. return lines2.join( '\n' );
  40964. }
  40965. /**
  40966. * Gets the shader compilation errors from the info log.
  40967. *
  40968. * @private
  40969. * @param {WebGL2RenderingContext} gl - The rendering context.
  40970. * @param {WebGLShader} shader - The WebGL shader object.
  40971. * @param {String} type - The shader type.
  40972. * @return {String} The shader errors.
  40973. */
  40974. _getShaderErrors( gl, shader, type ) {
  40975. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  40976. const errors = gl.getShaderInfoLog( shader ).trim();
  40977. if ( status && errors === '' ) return '';
  40978. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  40979. if ( errorMatches ) {
  40980. const errorLine = parseInt( errorMatches[ 1 ] );
  40981. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  40982. } else {
  40983. return errors;
  40984. }
  40985. }
  40986. /**
  40987. * Logs shader compilation errors.
  40988. *
  40989. * @private
  40990. * @param {WebGLProgram} programGPU - The WebGL program.
  40991. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  40992. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  40993. */
  40994. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  40995. if ( this.renderer.debug.checkShaderErrors ) {
  40996. const gl = this.gl;
  40997. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  40998. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  40999. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  41000. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  41001. } else {
  41002. // default error reporting
  41003. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  41004. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  41005. console.error(
  41006. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  41007. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  41008. 'Program Info Log: ' + programLog + '\n' +
  41009. vertexErrors + '\n' +
  41010. fragmentErrors
  41011. );
  41012. }
  41013. } else if ( programLog !== '' ) {
  41014. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  41015. }
  41016. }
  41017. }
  41018. /**
  41019. * Completes the shader program setup for the given render object.
  41020. *
  41021. * @private
  41022. * @param {RenderObject} renderObject - The render object.
  41023. * @param {RenderPipeline} pipeline - The render pipeline.
  41024. */
  41025. _completeCompile( renderObject, pipeline ) {
  41026. const { state, gl } = this;
  41027. const pipelineData = this.get( pipeline );
  41028. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  41029. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41030. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41031. }
  41032. state.useProgram( programGPU );
  41033. // Bindings
  41034. const bindings = renderObject.getBindings();
  41035. this._setupBindings( bindings, programGPU );
  41036. //
  41037. this.set( pipeline, {
  41038. programGPU
  41039. } );
  41040. }
  41041. /**
  41042. * Creates a compute pipeline for the given compute node.
  41043. *
  41044. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41045. * @param {Array<BindGroup>} bindings - The bindings.
  41046. */
  41047. createComputePipeline( computePipeline, bindings ) {
  41048. const { state, gl } = this;
  41049. // Program
  41050. const fragmentProgram = {
  41051. stage: 'fragment',
  41052. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  41053. };
  41054. this.createProgram( fragmentProgram );
  41055. const { computeProgram } = computePipeline;
  41056. const programGPU = gl.createProgram();
  41057. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  41058. const vertexShader = this.get( computeProgram ).shaderGPU;
  41059. const transforms = computeProgram.transforms;
  41060. const transformVaryingNames = [];
  41061. const transformAttributeNodes = [];
  41062. for ( let i = 0; i < transforms.length; i ++ ) {
  41063. const transform = transforms[ i ];
  41064. transformVaryingNames.push( transform.varyingName );
  41065. transformAttributeNodes.push( transform.attributeNode );
  41066. }
  41067. gl.attachShader( programGPU, fragmentShader );
  41068. gl.attachShader( programGPU, vertexShader );
  41069. gl.transformFeedbackVaryings(
  41070. programGPU,
  41071. transformVaryingNames,
  41072. gl.SEPARATE_ATTRIBS
  41073. );
  41074. gl.linkProgram( programGPU );
  41075. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  41076. this._logProgramError( programGPU, fragmentShader, vertexShader );
  41077. }
  41078. state.useProgram( programGPU );
  41079. // Bindings
  41080. this._setupBindings( bindings, programGPU );
  41081. const attributeNodes = computeProgram.attributes;
  41082. const attributes = [];
  41083. const transformBuffers = [];
  41084. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  41085. const attribute = attributeNodes[ i ].node.attribute;
  41086. attributes.push( attribute );
  41087. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41088. }
  41089. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  41090. const attribute = transformAttributeNodes[ i ].attribute;
  41091. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41092. const attributeData = this.get( attribute );
  41093. transformBuffers.push( attributeData );
  41094. }
  41095. //
  41096. this.set( computePipeline, {
  41097. programGPU,
  41098. transformBuffers,
  41099. attributes
  41100. } );
  41101. }
  41102. /**
  41103. * Creates bindings from the given bind group definition.
  41104. *
  41105. * @param {BindGroup} bindGroup - The bind group.
  41106. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41107. * @param {Number} cacheIndex - The cache index.
  41108. * @param {Number} version - The version.
  41109. */
  41110. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  41111. if ( this._knownBindings.has( bindings ) === false ) {
  41112. this._knownBindings.add( bindings );
  41113. let uniformBuffers = 0;
  41114. let textures = 0;
  41115. for ( const bindGroup of bindings ) {
  41116. this.set( bindGroup, {
  41117. textures: textures,
  41118. uniformBuffers: uniformBuffers
  41119. } );
  41120. for ( const binding of bindGroup.bindings ) {
  41121. if ( binding.isUniformBuffer ) uniformBuffers ++;
  41122. if ( binding.isSampledTexture ) textures ++;
  41123. }
  41124. }
  41125. }
  41126. this.updateBindings( bindGroup, bindings );
  41127. }
  41128. /**
  41129. * Updates the given bind group definition.
  41130. *
  41131. * @param {BindGroup} bindGroup - The bind group.
  41132. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41133. * @param {Number} cacheIndex - The cache index.
  41134. * @param {Number} version - The version.
  41135. */
  41136. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  41137. const { gl } = this;
  41138. const bindGroupData = this.get( bindGroup );
  41139. let i = bindGroupData.uniformBuffers;
  41140. let t = bindGroupData.textures;
  41141. for ( const binding of bindGroup.bindings ) {
  41142. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41143. const data = binding.buffer;
  41144. const bufferGPU = gl.createBuffer();
  41145. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41146. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41147. this.set( binding, {
  41148. index: i ++,
  41149. bufferGPU
  41150. } );
  41151. } else if ( binding.isSampledTexture ) {
  41152. const { textureGPU, glTextureType } = this.get( binding.texture );
  41153. this.set( binding, {
  41154. index: t ++,
  41155. textureGPU,
  41156. glTextureType
  41157. } );
  41158. }
  41159. }
  41160. }
  41161. /**
  41162. * Updates a buffer binding.
  41163. *
  41164. * @param {Buffer} binding - The buffer binding to update.
  41165. */
  41166. updateBinding( binding ) {
  41167. const gl = this.gl;
  41168. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41169. const bindingData = this.get( binding );
  41170. const bufferGPU = bindingData.bufferGPU;
  41171. const data = binding.buffer;
  41172. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  41173. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  41174. }
  41175. }
  41176. // attributes
  41177. /**
  41178. * Creates the GPU buffer of an indexed shader attribute.
  41179. *
  41180. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  41181. */
  41182. createIndexAttribute( attribute ) {
  41183. const gl = this.gl;
  41184. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  41185. }
  41186. /**
  41187. * Creates the GPU buffer of a shader attribute.
  41188. *
  41189. * @param {BufferAttribute} attribute - The buffer attribute.
  41190. */
  41191. createAttribute( attribute ) {
  41192. if ( this.has( attribute ) ) return;
  41193. const gl = this.gl;
  41194. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41195. }
  41196. /**
  41197. * Creates the GPU buffer of a storage attribute.
  41198. *
  41199. * @param {BufferAttribute} attribute - The buffer attribute.
  41200. */
  41201. createStorageAttribute( attribute ) {
  41202. if ( this.has( attribute ) ) return;
  41203. const gl = this.gl;
  41204. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  41205. }
  41206. /**
  41207. * Updates the GPU buffer of a shader attribute.
  41208. *
  41209. * @param {BufferAttribute} attribute - The buffer attribute to update.
  41210. */
  41211. updateAttribute( attribute ) {
  41212. this.attributeUtils.updateAttribute( attribute );
  41213. }
  41214. /**
  41215. * Destroys the GPU buffer of a shader attribute.
  41216. *
  41217. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  41218. */
  41219. destroyAttribute( attribute ) {
  41220. this.attributeUtils.destroyAttribute( attribute );
  41221. }
  41222. /**
  41223. * Checks if the given feature is supported by the backend.
  41224. *
  41225. * @param {String} name - The feature's name.
  41226. * @return {Boolean} Whether the feature is supported or not.
  41227. */
  41228. hasFeature( name ) {
  41229. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  41230. const extensions = this.extensions;
  41231. for ( let i = 0; i < keysMatching.length; i ++ ) {
  41232. if ( extensions.has( keysMatching[ i ] ) ) return true;
  41233. }
  41234. return false;
  41235. }
  41236. /**
  41237. * Returns the maximum anisotropy texture filtering value.
  41238. *
  41239. * @return {Number} The maximum anisotropy texture filtering value.
  41240. */
  41241. getMaxAnisotropy() {
  41242. return this.capabilities.getMaxAnisotropy();
  41243. }
  41244. /**
  41245. * Copies data of the given source texture to the given destination texture.
  41246. *
  41247. * @param {Texture} srcTexture - The source texture.
  41248. * @param {Texture} dstTexture - The destination texture.
  41249. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  41250. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  41251. * @param {Number} [level=0] - The mip level to copy.
  41252. */
  41253. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  41254. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, level );
  41255. }
  41256. /**
  41257. * Copies the current bound framebuffer to the given texture.
  41258. *
  41259. * @param {Texture} texture - The destination texture.
  41260. * @param {RenderContext} renderContext - The render context.
  41261. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41262. */
  41263. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  41264. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  41265. }
  41266. /**
  41267. * Configures the active framebuffer from the given render context.
  41268. *
  41269. * @private
  41270. * @param {RenderContext} descriptor - The render context.
  41271. */
  41272. _setFramebuffer( descriptor ) {
  41273. const { gl, state } = this;
  41274. let currentFrameBuffer = null;
  41275. if ( descriptor.textures !== null ) {
  41276. const renderTarget = descriptor.renderTarget;
  41277. const renderTargetContextData = this.get( renderTarget );
  41278. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  41279. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  41280. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  41281. const isRenderTargetArray = renderTarget.isRenderTargetArray === true;
  41282. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  41283. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  41284. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  41285. const cacheKey = getCacheKey( descriptor );
  41286. let fb;
  41287. if ( isCube ) {
  41288. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  41289. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  41290. } else if ( isXRRenderTarget ) {
  41291. fb = this._xrFamebuffer;
  41292. } else {
  41293. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  41294. fb = renderTargetContextData.framebuffers[ cacheKey ];
  41295. }
  41296. if ( fb === undefined ) {
  41297. fb = gl.createFramebuffer();
  41298. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  41299. const textures = descriptor.textures;
  41300. if ( isCube ) {
  41301. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  41302. const { textureGPU } = this.get( textures[ 0 ] );
  41303. const cubeFace = this.renderer._activeCubeFace;
  41304. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  41305. } else {
  41306. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  41307. for ( let i = 0; i < textures.length; i ++ ) {
  41308. const texture = textures[ i ];
  41309. const textureData = this.get( texture );
  41310. textureData.renderTarget = descriptor.renderTarget;
  41311. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41312. const attachment = gl.COLOR_ATTACHMENT0 + i;
  41313. if ( isRenderTarget3D || isRenderTargetArray ) {
  41314. const layer = this.renderer._activeCubeFace;
  41315. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  41316. } else {
  41317. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41318. }
  41319. }
  41320. state.drawBuffers( descriptor, fb );
  41321. }
  41322. if ( descriptor.depthTexture !== null ) {
  41323. const textureData = this.get( descriptor.depthTexture );
  41324. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41325. textureData.renderTarget = descriptor.renderTarget;
  41326. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  41327. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  41328. }
  41329. }
  41330. if ( samples > 0 ) {
  41331. if ( msaaFb === undefined ) {
  41332. const invalidationArray = [];
  41333. msaaFb = gl.createFramebuffer();
  41334. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  41335. const msaaRenderbuffers = [];
  41336. const textures = descriptor.textures;
  41337. for ( let i = 0; i < textures.length; i ++ ) {
  41338. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  41339. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41340. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  41341. if ( depthBuffer ) {
  41342. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41343. invalidationArray.push( depthStyle );
  41344. }
  41345. const texture = descriptor.textures[ i ];
  41346. const textureData = this.get( texture );
  41347. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  41348. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  41349. }
  41350. renderTargetContextData.msaaFrameBuffer = msaaFb;
  41351. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  41352. if ( depthRenderbuffer === undefined ) {
  41353. depthRenderbuffer = gl.createRenderbuffer();
  41354. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor );
  41355. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  41356. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  41357. invalidationArray.push( depthStyle );
  41358. }
  41359. renderTargetContextData.invalidationArray = invalidationArray;
  41360. }
  41361. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  41362. } else {
  41363. currentFrameBuffer = fb;
  41364. }
  41365. }
  41366. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  41367. }
  41368. /**
  41369. * Computes the VAO key for the given index and attributes.
  41370. *
  41371. * @private
  41372. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  41373. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  41374. * @return {String} The VAO key.
  41375. */
  41376. _getVaoKey( index, attributes ) {
  41377. let key = '';
  41378. if ( index !== null ) {
  41379. const indexData = this.get( index );
  41380. key += ':' + indexData.id;
  41381. }
  41382. for ( let i = 0; i < attributes.length; i ++ ) {
  41383. const attributeData = this.get( attributes[ i ] );
  41384. key += ':' + attributeData.id;
  41385. }
  41386. return key;
  41387. }
  41388. /**
  41389. * Creates a VAO from the index and attributes.
  41390. *
  41391. * @private
  41392. * @param {BufferAttribute?} index - The index. `null` for non-indexed geometries.
  41393. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  41394. * @return {Object} The VAO data.
  41395. */
  41396. _createVao( index, attributes ) {
  41397. const { gl } = this;
  41398. const vaoGPU = gl.createVertexArray();
  41399. let key = '';
  41400. let staticVao = true;
  41401. gl.bindVertexArray( vaoGPU );
  41402. if ( index !== null ) {
  41403. const indexData = this.get( index );
  41404. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexData.bufferGPU );
  41405. key += ':' + indexData.id;
  41406. }
  41407. for ( let i = 0; i < attributes.length; i ++ ) {
  41408. const attribute = attributes[ i ];
  41409. const attributeData = this.get( attribute );
  41410. key += ':' + attributeData.id;
  41411. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  41412. gl.enableVertexAttribArray( i );
  41413. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) staticVao = false;
  41414. let stride, offset;
  41415. if ( attribute.isInterleavedBufferAttribute === true ) {
  41416. stride = attribute.data.stride * attributeData.bytesPerElement;
  41417. offset = attribute.offset * attributeData.bytesPerElement;
  41418. } else {
  41419. stride = 0;
  41420. offset = 0;
  41421. }
  41422. if ( attributeData.isInteger ) {
  41423. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  41424. } else {
  41425. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  41426. }
  41427. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  41428. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  41429. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  41430. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  41431. }
  41432. }
  41433. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  41434. this.vaoCache[ key ] = vaoGPU;
  41435. return { vaoGPU, staticVao };
  41436. }
  41437. /**
  41438. * Creates a transform feedback from the given transform buffers.
  41439. *
  41440. * @private
  41441. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  41442. * @return {WebGLTransformFeedback} The transform feedback.
  41443. */
  41444. _getTransformFeedback( transformBuffers ) {
  41445. let key = '';
  41446. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41447. key += ':' + transformBuffers[ i ].id;
  41448. }
  41449. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  41450. if ( transformFeedbackGPU !== undefined ) {
  41451. return transformFeedbackGPU;
  41452. }
  41453. const { gl } = this;
  41454. transformFeedbackGPU = gl.createTransformFeedback();
  41455. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  41456. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  41457. const attributeData = transformBuffers[ i ];
  41458. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  41459. }
  41460. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  41461. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  41462. return transformFeedbackGPU;
  41463. }
  41464. /**
  41465. * Setups the given bindings.
  41466. *
  41467. * @private
  41468. * @param {Array<BindGroup>} bindings - The bindings.
  41469. * @param {WebGLProgram} programGPU - The WebGL program.
  41470. */
  41471. _setupBindings( bindings, programGPU ) {
  41472. const gl = this.gl;
  41473. for ( const bindGroup of bindings ) {
  41474. for ( const binding of bindGroup.bindings ) {
  41475. const bindingData = this.get( binding );
  41476. const index = bindingData.index;
  41477. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41478. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  41479. gl.uniformBlockBinding( programGPU, location, index );
  41480. } else if ( binding.isSampledTexture ) {
  41481. const location = gl.getUniformLocation( programGPU, binding.name );
  41482. gl.uniform1i( location, index );
  41483. }
  41484. }
  41485. }
  41486. }
  41487. /**
  41488. * Binds the given uniforms.
  41489. *
  41490. * @private
  41491. * @param {Array<BindGroup>} bindings - The bindings.
  41492. */
  41493. _bindUniforms( bindings ) {
  41494. const { gl, state } = this;
  41495. for ( const bindGroup of bindings ) {
  41496. for ( const binding of bindGroup.bindings ) {
  41497. const bindingData = this.get( binding );
  41498. const index = bindingData.index;
  41499. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  41500. // TODO USE bindBufferRange to group multiple uniform buffers
  41501. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  41502. } else if ( binding.isSampledTexture ) {
  41503. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  41504. }
  41505. }
  41506. }
  41507. }
  41508. /**
  41509. * Frees internal resources.
  41510. */
  41511. dispose() {
  41512. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  41513. }
  41514. }
  41515. const GPUPrimitiveTopology = {
  41516. PointList: 'point-list',
  41517. LineList: 'line-list',
  41518. LineStrip: 'line-strip',
  41519. TriangleList: 'triangle-list',
  41520. TriangleStrip: 'triangle-strip',
  41521. };
  41522. const GPUCompareFunction = {
  41523. Never: 'never',
  41524. Less: 'less',
  41525. Equal: 'equal',
  41526. LessEqual: 'less-equal',
  41527. Greater: 'greater',
  41528. NotEqual: 'not-equal',
  41529. GreaterEqual: 'greater-equal',
  41530. Always: 'always'
  41531. };
  41532. const GPUStoreOp = {
  41533. Store: 'store',
  41534. Discard: 'discard'
  41535. };
  41536. const GPULoadOp = {
  41537. Load: 'load',
  41538. Clear: 'clear'
  41539. };
  41540. const GPUFrontFace = {
  41541. CCW: 'ccw',
  41542. CW: 'cw'
  41543. };
  41544. const GPUCullMode = {
  41545. None: 'none',
  41546. Front: 'front',
  41547. Back: 'back'
  41548. };
  41549. const GPUIndexFormat = {
  41550. Uint16: 'uint16',
  41551. Uint32: 'uint32'
  41552. };
  41553. const GPUTextureFormat = {
  41554. // 8-bit formats
  41555. R8Unorm: 'r8unorm',
  41556. R8Snorm: 'r8snorm',
  41557. R8Uint: 'r8uint',
  41558. R8Sint: 'r8sint',
  41559. // 16-bit formats
  41560. R16Uint: 'r16uint',
  41561. R16Sint: 'r16sint',
  41562. R16Float: 'r16float',
  41563. RG8Unorm: 'rg8unorm',
  41564. RG8Snorm: 'rg8snorm',
  41565. RG8Uint: 'rg8uint',
  41566. RG8Sint: 'rg8sint',
  41567. // 32-bit formats
  41568. R32Uint: 'r32uint',
  41569. R32Sint: 'r32sint',
  41570. R32Float: 'r32float',
  41571. RG16Uint: 'rg16uint',
  41572. RG16Sint: 'rg16sint',
  41573. RG16Float: 'rg16float',
  41574. RGBA8Unorm: 'rgba8unorm',
  41575. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  41576. RGBA8Snorm: 'rgba8snorm',
  41577. RGBA8Uint: 'rgba8uint',
  41578. RGBA8Sint: 'rgba8sint',
  41579. BGRA8Unorm: 'bgra8unorm',
  41580. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  41581. // Packed 32-bit formats
  41582. RGB9E5UFloat: 'rgb9e5ufloat',
  41583. RGB10A2Unorm: 'rgb10a2unorm',
  41584. RG11B10uFloat: 'rgb10a2unorm',
  41585. // 64-bit formats
  41586. RG32Uint: 'rg32uint',
  41587. RG32Sint: 'rg32sint',
  41588. RG32Float: 'rg32float',
  41589. RGBA16Uint: 'rgba16uint',
  41590. RGBA16Sint: 'rgba16sint',
  41591. RGBA16Float: 'rgba16float',
  41592. // 128-bit formats
  41593. RGBA32Uint: 'rgba32uint',
  41594. RGBA32Sint: 'rgba32sint',
  41595. RGBA32Float: 'rgba32float',
  41596. // Depth and stencil formats
  41597. Stencil8: 'stencil8',
  41598. Depth16Unorm: 'depth16unorm',
  41599. Depth24Plus: 'depth24plus',
  41600. Depth24PlusStencil8: 'depth24plus-stencil8',
  41601. Depth32Float: 'depth32float',
  41602. // 'depth32float-stencil8' extension
  41603. Depth32FloatStencil8: 'depth32float-stencil8',
  41604. // BC compressed formats usable if 'texture-compression-bc' is both
  41605. // supported by the device/user agent and enabled in requestDevice.
  41606. BC1RGBAUnorm: 'bc1-rgba-unorm',
  41607. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  41608. BC2RGBAUnorm: 'bc2-rgba-unorm',
  41609. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  41610. BC3RGBAUnorm: 'bc3-rgba-unorm',
  41611. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  41612. BC4RUnorm: 'bc4-r-unorm',
  41613. BC4RSnorm: 'bc4-r-snorm',
  41614. BC5RGUnorm: 'bc5-rg-unorm',
  41615. BC5RGSnorm: 'bc5-rg-snorm',
  41616. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  41617. BC6HRGBFloat: 'bc6h-rgb-float',
  41618. BC7RGBAUnorm: 'bc7-rgba-unorm',
  41619. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  41620. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  41621. // supported by the device/user agent and enabled in requestDevice.
  41622. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  41623. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  41624. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  41625. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  41626. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  41627. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  41628. EACR11Unorm: 'eac-r11unorm',
  41629. EACR11Snorm: 'eac-r11snorm',
  41630. EACRG11Unorm: 'eac-rg11unorm',
  41631. EACRG11Snorm: 'eac-rg11snorm',
  41632. // ASTC compressed formats usable if 'texture-compression-astc' is both
  41633. // supported by the device/user agent and enabled in requestDevice.
  41634. ASTC4x4Unorm: 'astc-4x4-unorm',
  41635. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  41636. ASTC5x4Unorm: 'astc-5x4-unorm',
  41637. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  41638. ASTC5x5Unorm: 'astc-5x5-unorm',
  41639. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  41640. ASTC6x5Unorm: 'astc-6x5-unorm',
  41641. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  41642. ASTC6x6Unorm: 'astc-6x6-unorm',
  41643. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  41644. ASTC8x5Unorm: 'astc-8x5-unorm',
  41645. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  41646. ASTC8x6Unorm: 'astc-8x6-unorm',
  41647. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  41648. ASTC8x8Unorm: 'astc-8x8-unorm',
  41649. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  41650. ASTC10x5Unorm: 'astc-10x5-unorm',
  41651. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  41652. ASTC10x6Unorm: 'astc-10x6-unorm',
  41653. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  41654. ASTC10x8Unorm: 'astc-10x8-unorm',
  41655. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  41656. ASTC10x10Unorm: 'astc-10x10-unorm',
  41657. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  41658. ASTC12x10Unorm: 'astc-12x10-unorm',
  41659. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  41660. ASTC12x12Unorm: 'astc-12x12-unorm',
  41661. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  41662. };
  41663. const GPUAddressMode = {
  41664. ClampToEdge: 'clamp-to-edge',
  41665. Repeat: 'repeat',
  41666. MirrorRepeat: 'mirror-repeat'
  41667. };
  41668. const GPUFilterMode = {
  41669. Linear: 'linear',
  41670. Nearest: 'nearest'
  41671. };
  41672. const GPUBlendFactor = {
  41673. Zero: 'zero',
  41674. One: 'one',
  41675. Src: 'src',
  41676. OneMinusSrc: 'one-minus-src',
  41677. SrcAlpha: 'src-alpha',
  41678. OneMinusSrcAlpha: 'one-minus-src-alpha',
  41679. Dst: 'dst',
  41680. OneMinusDstColor: 'one-minus-dst',
  41681. DstAlpha: 'dst-alpha',
  41682. OneMinusDstAlpha: 'one-minus-dst-alpha',
  41683. SrcAlphaSaturated: 'src-alpha-saturated',
  41684. Constant: 'constant',
  41685. OneMinusConstant: 'one-minus-constant'
  41686. };
  41687. const GPUBlendOperation = {
  41688. Add: 'add',
  41689. Subtract: 'subtract',
  41690. ReverseSubtract: 'reverse-subtract',
  41691. Min: 'min',
  41692. Max: 'max'
  41693. };
  41694. const GPUColorWriteFlags = {
  41695. None: 0,
  41696. Red: 0x1,
  41697. Green: 0x2,
  41698. Blue: 0x4,
  41699. Alpha: 0x8,
  41700. All: 0xF
  41701. };
  41702. const GPUStencilOperation = {
  41703. Keep: 'keep',
  41704. Zero: 'zero',
  41705. Replace: 'replace',
  41706. Invert: 'invert',
  41707. IncrementClamp: 'increment-clamp',
  41708. DecrementClamp: 'decrement-clamp',
  41709. IncrementWrap: 'increment-wrap',
  41710. DecrementWrap: 'decrement-wrap'
  41711. };
  41712. const GPUBufferBindingType = {
  41713. Uniform: 'uniform',
  41714. Storage: 'storage',
  41715. ReadOnlyStorage: 'read-only-storage'
  41716. };
  41717. const GPUStorageTextureAccess = {
  41718. WriteOnly: 'write-only',
  41719. ReadOnly: 'read-only',
  41720. ReadWrite: 'read-write',
  41721. };
  41722. const GPUTextureSampleType = {
  41723. Float: 'float',
  41724. UnfilterableFloat: 'unfilterable-float',
  41725. Depth: 'depth',
  41726. SInt: 'sint',
  41727. UInt: 'uint'
  41728. };
  41729. const GPUTextureDimension = {
  41730. OneD: '1d',
  41731. TwoD: '2d',
  41732. ThreeD: '3d'
  41733. };
  41734. const GPUTextureViewDimension = {
  41735. OneD: '1d',
  41736. TwoD: '2d',
  41737. TwoDArray: '2d-array',
  41738. Cube: 'cube',
  41739. CubeArray: 'cube-array',
  41740. ThreeD: '3d'
  41741. };
  41742. const GPUTextureAspect = {
  41743. All: 'all',
  41744. StencilOnly: 'stencil-only',
  41745. DepthOnly: 'depth-only'
  41746. };
  41747. const GPUInputStepMode = {
  41748. Vertex: 'vertex',
  41749. Instance: 'instance'
  41750. };
  41751. const GPUFeatureName = {
  41752. DepthClipControl: 'depth-clip-control',
  41753. Depth32FloatStencil8: 'depth32float-stencil8',
  41754. TextureCompressionBC: 'texture-compression-bc',
  41755. TextureCompressionETC2: 'texture-compression-etc2',
  41756. TextureCompressionASTC: 'texture-compression-astc',
  41757. TimestampQuery: 'timestamp-query',
  41758. IndirectFirstInstance: 'indirect-first-instance',
  41759. ShaderF16: 'shader-f16',
  41760. RG11B10UFloat: 'rg11b10ufloat-renderable',
  41761. BGRA8UNormStorage: 'bgra8unorm-storage',
  41762. Float32Filterable: 'float32-filterable',
  41763. ClipDistances: 'clip-distances',
  41764. DualSourceBlending: 'dual-source-blending',
  41765. Subgroups: 'subgroups'
  41766. };
  41767. /**
  41768. * Represents a sampler binding type.
  41769. *
  41770. * @private
  41771. * @augments Binding
  41772. */
  41773. class Sampler extends Binding {
  41774. /**
  41775. * Constructs a new sampler.
  41776. *
  41777. * @param {String} name - The samplers's name.
  41778. * @param {Texture?} texture - The texture this binding is referring to.
  41779. */
  41780. constructor( name, texture ) {
  41781. super( name );
  41782. /**
  41783. * The texture the sampler is referring to.
  41784. *
  41785. * @type {Texture?}
  41786. */
  41787. this.texture = texture;
  41788. /**
  41789. * The binding's version.
  41790. *
  41791. * @type {Number}
  41792. */
  41793. this.version = texture ? texture.version : 0;
  41794. /**
  41795. * This flag can be used for type testing.
  41796. *
  41797. * @type {Boolean}
  41798. * @readonly
  41799. * @default true
  41800. */
  41801. this.isSampler = true;
  41802. }
  41803. }
  41804. /**
  41805. * A special form of sampler binding type.
  41806. * It's texture value is managed by a node object.
  41807. *
  41808. * @private
  41809. * @augments Sampler
  41810. */
  41811. class NodeSampler extends Sampler {
  41812. /**
  41813. * Constructs a new node-based sampler.
  41814. *
  41815. * @param {String} name - The samplers's name.
  41816. * @param {TextureNode} textureNode - The texture node.
  41817. * @param {UniformGroupNode} groupNode - The uniform group node.
  41818. */
  41819. constructor( name, textureNode, groupNode ) {
  41820. super( name, textureNode ? textureNode.value : null );
  41821. /**
  41822. * The texture node.
  41823. *
  41824. * @type {TextureNode}
  41825. */
  41826. this.textureNode = textureNode;
  41827. /**
  41828. * The uniform group node.
  41829. *
  41830. * @type {UniformGroupNode}
  41831. */
  41832. this.groupNode = groupNode;
  41833. }
  41834. /**
  41835. * Updates the texture value of this sampler.
  41836. */
  41837. update() {
  41838. this.texture = this.textureNode.value;
  41839. }
  41840. }
  41841. /**
  41842. * Represents a storage buffer binding type.
  41843. *
  41844. * @private
  41845. * @augments Buffer
  41846. */
  41847. class StorageBuffer extends Buffer {
  41848. /**
  41849. * Constructs a new uniform buffer.
  41850. *
  41851. * @param {String} name - The buffer's name.
  41852. * @param {BufferAttribute} attribute - The buffer attribute.
  41853. */
  41854. constructor( name, attribute ) {
  41855. super( name, attribute ? attribute.array : null );
  41856. /**
  41857. * This flag can be used for type testing.
  41858. *
  41859. * @type {BufferAttribute}
  41860. */
  41861. this.attribute = attribute;
  41862. /**
  41863. * This flag can be used for type testing.
  41864. *
  41865. * @type {Boolean}
  41866. * @readonly
  41867. * @default true
  41868. */
  41869. this.isStorageBuffer = true;
  41870. }
  41871. }
  41872. let _id = 0;
  41873. /**
  41874. * A special form of storage buffer binding type.
  41875. * It's buffer value is managed by a node object.
  41876. *
  41877. * @private
  41878. * @augments StorageBuffer
  41879. */
  41880. class NodeStorageBuffer extends StorageBuffer {
  41881. /**
  41882. * Constructs a new node-based storage buffer.
  41883. *
  41884. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  41885. * @param {UniformGroupNode} groupNode - The uniform group node.
  41886. */
  41887. constructor( nodeUniform, groupNode ) {
  41888. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  41889. /**
  41890. * The node uniform.
  41891. *
  41892. * @type {StorageBufferNode}
  41893. */
  41894. this.nodeUniform = nodeUniform;
  41895. /**
  41896. * The access type.
  41897. *
  41898. * @type {String}
  41899. */
  41900. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  41901. /**
  41902. * The uniform group node.
  41903. *
  41904. * @type {UniformGroupNode}
  41905. */
  41906. this.groupNode = groupNode;
  41907. }
  41908. /**
  41909. * The storage buffer.
  41910. *
  41911. * @type {BufferAttribute}
  41912. */
  41913. get buffer() {
  41914. return this.nodeUniform.value;
  41915. }
  41916. }
  41917. /**
  41918. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  41919. *
  41920. * @private
  41921. */
  41922. class WebGPUTexturePassUtils extends DataMap {
  41923. /**
  41924. * Constructs a new utility object.
  41925. *
  41926. * @param {GPUDevice} device - The WebGPU device.
  41927. */
  41928. constructor( device ) {
  41929. super();
  41930. /**
  41931. * The WebGPU device.
  41932. *
  41933. * @type {GPUDevice}
  41934. */
  41935. this.device = device;
  41936. const mipmapVertexSource = `
  41937. struct VarysStruct {
  41938. @builtin( position ) Position: vec4<f32>,
  41939. @location( 0 ) vTex : vec2<f32>
  41940. };
  41941. @vertex
  41942. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  41943. var Varys : VarysStruct;
  41944. var pos = array< vec2<f32>, 4 >(
  41945. vec2<f32>( -1.0, 1.0 ),
  41946. vec2<f32>( 1.0, 1.0 ),
  41947. vec2<f32>( -1.0, -1.0 ),
  41948. vec2<f32>( 1.0, -1.0 )
  41949. );
  41950. var tex = array< vec2<f32>, 4 >(
  41951. vec2<f32>( 0.0, 0.0 ),
  41952. vec2<f32>( 1.0, 0.0 ),
  41953. vec2<f32>( 0.0, 1.0 ),
  41954. vec2<f32>( 1.0, 1.0 )
  41955. );
  41956. Varys.vTex = tex[ vertexIndex ];
  41957. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  41958. return Varys;
  41959. }
  41960. `;
  41961. const mipmapFragmentSource = `
  41962. @group( 0 ) @binding( 0 )
  41963. var imgSampler : sampler;
  41964. @group( 0 ) @binding( 1 )
  41965. var img : texture_2d<f32>;
  41966. @fragment
  41967. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41968. return textureSample( img, imgSampler, vTex );
  41969. }
  41970. `;
  41971. const flipYFragmentSource = `
  41972. @group( 0 ) @binding( 0 )
  41973. var imgSampler : sampler;
  41974. @group( 0 ) @binding( 1 )
  41975. var img : texture_2d<f32>;
  41976. @fragment
  41977. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  41978. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  41979. }
  41980. `;
  41981. /**
  41982. * The mipmap GPU sampler.
  41983. *
  41984. * @type {GPUSampler}
  41985. */
  41986. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  41987. /**
  41988. * The flipY GPU sampler.
  41989. *
  41990. * @type {GPUSampler}
  41991. */
  41992. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  41993. /**
  41994. * A cache for GPU render pipelines used for copy/transfer passes.
  41995. * Every texture format requires a unique pipeline.
  41996. *
  41997. * @type {Object<String,GPURenderPipeline>}
  41998. */
  41999. this.transferPipelines = {};
  42000. /**
  42001. * A cache for GPU render pipelines used for flipY passes.
  42002. * Every texture format requires a unique pipeline.
  42003. *
  42004. * @type {Object<String,GPURenderPipeline>}
  42005. */
  42006. this.flipYPipelines = {};
  42007. /**
  42008. * The mipmap vertex shader module.
  42009. *
  42010. * @type {GPUShaderModule}
  42011. */
  42012. this.mipmapVertexShaderModule = device.createShaderModule( {
  42013. label: 'mipmapVertex',
  42014. code: mipmapVertexSource
  42015. } );
  42016. /**
  42017. * The mipmap fragment shader module.
  42018. *
  42019. * @type {GPUShaderModule}
  42020. */
  42021. this.mipmapFragmentShaderModule = device.createShaderModule( {
  42022. label: 'mipmapFragment',
  42023. code: mipmapFragmentSource
  42024. } );
  42025. /**
  42026. * The flipY fragment shader module.
  42027. *
  42028. * @type {GPUShaderModule}
  42029. */
  42030. this.flipYFragmentShaderModule = device.createShaderModule( {
  42031. label: 'flipYFragment',
  42032. code: flipYFragmentSource
  42033. } );
  42034. }
  42035. /**
  42036. * Returns a render pipeline for the internal copy render pass. The pass
  42037. * requires a unique render pipeline for each texture format.
  42038. *
  42039. * @param {String} format - The GPU texture format
  42040. * @return {GPURenderPipeline} The GPU render pipeline.
  42041. */
  42042. getTransferPipeline( format ) {
  42043. let pipeline = this.transferPipelines[ format ];
  42044. if ( pipeline === undefined ) {
  42045. pipeline = this.device.createRenderPipeline( {
  42046. label: `mipmap-${ format }`,
  42047. vertex: {
  42048. module: this.mipmapVertexShaderModule,
  42049. entryPoint: 'main'
  42050. },
  42051. fragment: {
  42052. module: this.mipmapFragmentShaderModule,
  42053. entryPoint: 'main',
  42054. targets: [ { format } ]
  42055. },
  42056. primitive: {
  42057. topology: GPUPrimitiveTopology.TriangleStrip,
  42058. stripIndexFormat: GPUIndexFormat.Uint32
  42059. },
  42060. layout: 'auto'
  42061. } );
  42062. this.transferPipelines[ format ] = pipeline;
  42063. }
  42064. return pipeline;
  42065. }
  42066. /**
  42067. * Returns a render pipeline for the flipY render pass. The pass
  42068. * requires a unique render pipeline for each texture format.
  42069. *
  42070. * @param {String} format - The GPU texture format
  42071. * @return {GPURenderPipeline} The GPU render pipeline.
  42072. */
  42073. getFlipYPipeline( format ) {
  42074. let pipeline = this.flipYPipelines[ format ];
  42075. if ( pipeline === undefined ) {
  42076. pipeline = this.device.createRenderPipeline( {
  42077. label: `flipY-${ format }`,
  42078. vertex: {
  42079. module: this.mipmapVertexShaderModule,
  42080. entryPoint: 'main'
  42081. },
  42082. fragment: {
  42083. module: this.flipYFragmentShaderModule,
  42084. entryPoint: 'main',
  42085. targets: [ { format } ]
  42086. },
  42087. primitive: {
  42088. topology: GPUPrimitiveTopology.TriangleStrip,
  42089. stripIndexFormat: GPUIndexFormat.Uint32
  42090. },
  42091. layout: 'auto'
  42092. } );
  42093. this.flipYPipelines[ format ] = pipeline;
  42094. }
  42095. return pipeline;
  42096. }
  42097. /**
  42098. * Flip the contents of the given GPU texture along its vertical axis.
  42099. *
  42100. * @param {GPUTexture} textureGPU - The GPU texture object.
  42101. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42102. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42103. */
  42104. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42105. const format = textureGPUDescriptor.format;
  42106. const { width, height } = textureGPUDescriptor.size;
  42107. const transferPipeline = this.getTransferPipeline( format );
  42108. const flipYPipeline = this.getFlipYPipeline( format );
  42109. const tempTexture = this.device.createTexture( {
  42110. size: { width, height, depthOrArrayLayers: 1 },
  42111. format,
  42112. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  42113. } );
  42114. const srcView = textureGPU.createView( {
  42115. baseMipLevel: 0,
  42116. mipLevelCount: 1,
  42117. dimension: GPUTextureViewDimension.TwoD,
  42118. baseArrayLayer
  42119. } );
  42120. const dstView = tempTexture.createView( {
  42121. baseMipLevel: 0,
  42122. mipLevelCount: 1,
  42123. dimension: GPUTextureViewDimension.TwoD,
  42124. baseArrayLayer: 0
  42125. } );
  42126. const commandEncoder = this.device.createCommandEncoder( {} );
  42127. const pass = ( pipeline, sourceView, destinationView ) => {
  42128. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42129. const bindGroup = this.device.createBindGroup( {
  42130. layout: bindGroupLayout,
  42131. entries: [ {
  42132. binding: 0,
  42133. resource: this.flipYSampler
  42134. }, {
  42135. binding: 1,
  42136. resource: sourceView
  42137. } ]
  42138. } );
  42139. const passEncoder = commandEncoder.beginRenderPass( {
  42140. colorAttachments: [ {
  42141. view: destinationView,
  42142. loadOp: GPULoadOp.Clear,
  42143. storeOp: GPUStoreOp.Store,
  42144. clearValue: [ 0, 0, 0, 0 ]
  42145. } ]
  42146. } );
  42147. passEncoder.setPipeline( pipeline );
  42148. passEncoder.setBindGroup( 0, bindGroup );
  42149. passEncoder.draw( 4, 1, 0, 0 );
  42150. passEncoder.end();
  42151. };
  42152. pass( transferPipeline, srcView, dstView );
  42153. pass( flipYPipeline, dstView, srcView );
  42154. this.device.queue.submit( [ commandEncoder.finish() ] );
  42155. tempTexture.destroy();
  42156. }
  42157. /**
  42158. * Generates mipmaps for the given GPU texture.
  42159. *
  42160. * @param {GPUTexture} textureGPU - The GPU texture object.
  42161. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42162. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42163. */
  42164. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  42165. const textureData = this.get( textureGPU );
  42166. if ( textureData.useCount === undefined ) {
  42167. textureData.useCount = 0;
  42168. textureData.layers = [];
  42169. }
  42170. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  42171. const commandEncoder = this.device.createCommandEncoder( {} );
  42172. this._mipmapRunBundles( commandEncoder, passes );
  42173. this.device.queue.submit( [ commandEncoder.finish() ] );
  42174. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  42175. textureData.useCount ++;
  42176. }
  42177. /**
  42178. * Since multiple copy render passes are required to generate mipmaps, the passes
  42179. * are managed as render bundles to improve performance.
  42180. *
  42181. * @param {GPUTexture} textureGPU - The GPU texture object.
  42182. * @param {Object} textureGPUDescriptor - The texture descriptor.
  42183. * @param {Number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  42184. * @return {Array} An array of render bundles.
  42185. */
  42186. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  42187. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  42188. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  42189. let srcView = textureGPU.createView( {
  42190. baseMipLevel: 0,
  42191. mipLevelCount: 1,
  42192. dimension: GPUTextureViewDimension.TwoD,
  42193. baseArrayLayer
  42194. } );
  42195. const passes = [];
  42196. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  42197. const bindGroup = this.device.createBindGroup( {
  42198. layout: bindGroupLayout,
  42199. entries: [ {
  42200. binding: 0,
  42201. resource: this.mipmapSampler
  42202. }, {
  42203. binding: 1,
  42204. resource: srcView
  42205. } ]
  42206. } );
  42207. const dstView = textureGPU.createView( {
  42208. baseMipLevel: i,
  42209. mipLevelCount: 1,
  42210. dimension: GPUTextureViewDimension.TwoD,
  42211. baseArrayLayer
  42212. } );
  42213. const passDescriptor = {
  42214. colorAttachments: [ {
  42215. view: dstView,
  42216. loadOp: GPULoadOp.Clear,
  42217. storeOp: GPUStoreOp.Store,
  42218. clearValue: [ 0, 0, 0, 0 ]
  42219. } ]
  42220. };
  42221. const passEncoder = this.device.createRenderBundleEncoder( {
  42222. colorFormats: [ textureGPUDescriptor.format ]
  42223. } );
  42224. passEncoder.setPipeline( pipeline );
  42225. passEncoder.setBindGroup( 0, bindGroup );
  42226. passEncoder.draw( 4, 1, 0, 0 );
  42227. passes.push( {
  42228. renderBundles: [ passEncoder.finish() ],
  42229. passDescriptor
  42230. } );
  42231. srcView = dstView;
  42232. }
  42233. return passes;
  42234. }
  42235. /**
  42236. * Executes the render bundles.
  42237. *
  42238. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  42239. * @param {Array} passes - An array of render bundles.
  42240. */
  42241. _mipmapRunBundles( commandEncoder, passes ) {
  42242. const levels = passes.length;
  42243. for ( let i = 0; i < levels; i ++ ) {
  42244. const pass = passes[ i ];
  42245. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  42246. passEncoder.executeBundles( pass.renderBundles );
  42247. passEncoder.end();
  42248. }
  42249. }
  42250. }
  42251. const _compareToWebGPU = {
  42252. [ NeverCompare ]: 'never',
  42253. [ LessCompare ]: 'less',
  42254. [ EqualCompare ]: 'equal',
  42255. [ LessEqualCompare ]: 'less-equal',
  42256. [ GreaterCompare ]: 'greater',
  42257. [ GreaterEqualCompare ]: 'greater-equal',
  42258. [ AlwaysCompare ]: 'always',
  42259. [ NotEqualCompare ]: 'not-equal'
  42260. };
  42261. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  42262. /**
  42263. * A WebGPU backend utility module for managing textures.
  42264. *
  42265. * @private
  42266. */
  42267. class WebGPUTextureUtils {
  42268. /**
  42269. * Constructs a new utility object.
  42270. *
  42271. * @param {WebGPUBackend} backend - The WebGPU backend.
  42272. */
  42273. constructor( backend ) {
  42274. /**
  42275. * A reference to the WebGPU backend.
  42276. *
  42277. * @type {WebGPUBackend}
  42278. */
  42279. this.backend = backend;
  42280. /**
  42281. * A reference to the pass utils.
  42282. *
  42283. * @type {WebGPUTexturePassUtils?}
  42284. * @default null
  42285. */
  42286. this._passUtils = null;
  42287. /**
  42288. * A dictionary for managing default textures. The key
  42289. * is the texture format, the value the texture object.
  42290. *
  42291. * @type {Object<String,Texture>}
  42292. */
  42293. this.defaultTexture = {};
  42294. /**
  42295. * A dictionary for managing default cube textures. The key
  42296. * is the texture format, the value the texture object.
  42297. *
  42298. * @type {Object<String,CubeTexture>}
  42299. */
  42300. this.defaultCubeTexture = {};
  42301. /**
  42302. * A default video frame.
  42303. *
  42304. * @type {VideoFrame?}
  42305. * @default null
  42306. */
  42307. this.defaultVideoFrame = null;
  42308. /**
  42309. * Represents the color attachment of the default framebuffer.
  42310. *
  42311. * @type {GPUTexture?}
  42312. * @default null
  42313. */
  42314. this.colorBuffer = null;
  42315. /**
  42316. * Represents the depth attachment of the default framebuffer.
  42317. *
  42318. * @type {DepthTexture}
  42319. */
  42320. this.depthTexture = new DepthTexture();
  42321. this.depthTexture.name = 'depthBuffer';
  42322. }
  42323. /**
  42324. * Creates a GPU sampler for the given texture.
  42325. *
  42326. * @param {Texture} texture - The texture to create the sampler for.
  42327. */
  42328. createSampler( texture ) {
  42329. const backend = this.backend;
  42330. const device = backend.device;
  42331. const textureGPU = backend.get( texture );
  42332. const samplerDescriptorGPU = {
  42333. addressModeU: this._convertAddressMode( texture.wrapS ),
  42334. addressModeV: this._convertAddressMode( texture.wrapT ),
  42335. addressModeW: this._convertAddressMode( texture.wrapR ),
  42336. magFilter: this._convertFilterMode( texture.magFilter ),
  42337. minFilter: this._convertFilterMode( texture.minFilter ),
  42338. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  42339. maxAnisotropy: 1
  42340. };
  42341. // anisotropy can only be used when all filter modes are set to linear.
  42342. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  42343. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  42344. }
  42345. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  42346. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  42347. }
  42348. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  42349. }
  42350. /**
  42351. * Creates a default texture for the given texture that can be used
  42352. * as a placeholder until the actual texture is ready for usage.
  42353. *
  42354. * @param {Texture} texture - The texture to create a default texture for.
  42355. */
  42356. createDefaultTexture( texture ) {
  42357. let textureGPU;
  42358. const format = getFormat( texture );
  42359. if ( texture.isCubeTexture ) {
  42360. textureGPU = this._getDefaultCubeTextureGPU( format );
  42361. } else if ( texture.isVideoTexture ) {
  42362. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  42363. } else {
  42364. textureGPU = this._getDefaultTextureGPU( format );
  42365. }
  42366. this.backend.get( texture ).texture = textureGPU;
  42367. }
  42368. /**
  42369. * Defines a texture on the GPU for the given texture object.
  42370. *
  42371. * @param {Texture} texture - The texture.
  42372. * @param {Object} [options={}] - Optional configuration parameter.
  42373. * @return {undefined}
  42374. */
  42375. createTexture( texture, options = {} ) {
  42376. const backend = this.backend;
  42377. const textureData = backend.get( texture );
  42378. if ( textureData.initialized ) {
  42379. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  42380. }
  42381. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  42382. if ( options.levels === undefined ) options.levels = 1;
  42383. if ( options.depth === undefined ) options.depth = 1;
  42384. const { width, height, depth, levels } = options;
  42385. if ( texture.isFramebufferTexture ) {
  42386. if ( options.renderTarget ) {
  42387. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  42388. } else {
  42389. options.format = this.backend.utils.getPreferredCanvasFormat();
  42390. }
  42391. }
  42392. const dimension = this._getDimension( texture );
  42393. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  42394. textureData.format = format;
  42395. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  42396. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  42397. if ( texture.isStorageTexture === true ) {
  42398. usage |= GPUTextureUsage.STORAGE_BINDING;
  42399. }
  42400. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  42401. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  42402. }
  42403. const textureDescriptorGPU = {
  42404. label: texture.name,
  42405. size: {
  42406. width: width,
  42407. height: height,
  42408. depthOrArrayLayers: depth,
  42409. },
  42410. mipLevelCount: levels,
  42411. sampleCount: primarySamples,
  42412. dimension: dimension,
  42413. format: format,
  42414. usage: usage
  42415. };
  42416. // texture creation
  42417. if ( texture.isVideoTexture ) {
  42418. const video = texture.source.data;
  42419. const videoFrame = new VideoFrame( video );
  42420. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  42421. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  42422. videoFrame.close();
  42423. textureData.externalTexture = video;
  42424. } else {
  42425. if ( format === undefined ) {
  42426. console.warn( 'WebGPURenderer: Texture format not supported.' );
  42427. return this.createDefaultTexture( texture );
  42428. }
  42429. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  42430. }
  42431. if ( isMSAA ) {
  42432. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  42433. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  42434. msaaTextureDescriptorGPU.sampleCount = samples;
  42435. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  42436. }
  42437. textureData.initialized = true;
  42438. textureData.textureDescriptorGPU = textureDescriptorGPU;
  42439. }
  42440. /**
  42441. * Destroys the GPU data for the given texture object.
  42442. *
  42443. * @param {Texture} texture - The texture.
  42444. */
  42445. destroyTexture( texture ) {
  42446. const backend = this.backend;
  42447. const textureData = backend.get( texture );
  42448. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  42449. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  42450. backend.delete( texture );
  42451. }
  42452. /**
  42453. * Destroys the GPU sampler for the given texture.
  42454. *
  42455. * @param {Texture} texture - The texture to destroy the sampler for.
  42456. */
  42457. destroySampler( texture ) {
  42458. const backend = this.backend;
  42459. const textureData = backend.get( texture );
  42460. delete textureData.sampler;
  42461. }
  42462. /**
  42463. * Generates mipmaps for the given texture.
  42464. *
  42465. * @param {Texture} texture - The texture.
  42466. */
  42467. generateMipmaps( texture ) {
  42468. const textureData = this.backend.get( texture );
  42469. if ( texture.isCubeTexture ) {
  42470. for ( let i = 0; i < 6; i ++ ) {
  42471. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42472. }
  42473. } else {
  42474. const depth = texture.image.depth || 1;
  42475. for ( let i = 0; i < depth; i ++ ) {
  42476. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  42477. }
  42478. }
  42479. }
  42480. /**
  42481. * Returns the color buffer representing the color
  42482. * attachment of the default framebuffer.
  42483. *
  42484. * @return {GPUTexture} The color buffer.
  42485. */
  42486. getColorBuffer() {
  42487. if ( this.colorBuffer ) this.colorBuffer.destroy();
  42488. const backend = this.backend;
  42489. const { width, height } = backend.getDrawingBufferSize();
  42490. this.colorBuffer = backend.device.createTexture( {
  42491. label: 'colorBuffer',
  42492. size: {
  42493. width: width,
  42494. height: height,
  42495. depthOrArrayLayers: 1
  42496. },
  42497. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  42498. format: backend.utils.getPreferredCanvasFormat(),
  42499. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  42500. } );
  42501. return this.colorBuffer;
  42502. }
  42503. /**
  42504. * Returns the depth buffer representing the depth
  42505. * attachment of the default framebuffer.
  42506. *
  42507. * @param {Boolean} [depth=true] - Whether depth is enabled or not.
  42508. * @param {Boolean} [stencil=false] - Whether stencil is enabled or not.
  42509. * @return {GPUTexture} The depth buffer.
  42510. */
  42511. getDepthBuffer( depth = true, stencil = false ) {
  42512. const backend = this.backend;
  42513. const { width, height } = backend.getDrawingBufferSize();
  42514. const depthTexture = this.depthTexture;
  42515. const depthTextureGPU = backend.get( depthTexture ).texture;
  42516. let format, type;
  42517. if ( stencil ) {
  42518. format = DepthStencilFormat;
  42519. type = UnsignedInt248Type;
  42520. } else if ( depth ) {
  42521. format = DepthFormat;
  42522. type = UnsignedIntType;
  42523. }
  42524. if ( depthTextureGPU !== undefined ) {
  42525. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  42526. return depthTextureGPU;
  42527. }
  42528. this.destroyTexture( depthTexture );
  42529. }
  42530. depthTexture.name = 'depthBuffer';
  42531. depthTexture.format = format;
  42532. depthTexture.type = type;
  42533. depthTexture.image.width = width;
  42534. depthTexture.image.height = height;
  42535. this.createTexture( depthTexture, { width, height } );
  42536. return backend.get( depthTexture ).texture;
  42537. }
  42538. /**
  42539. * Uploads the updated texture data to the GPU.
  42540. *
  42541. * @param {Texture} texture - The texture.
  42542. * @param {Object} [options={}] - Optional configuration parameter.
  42543. */
  42544. updateTexture( texture, options ) {
  42545. const textureData = this.backend.get( texture );
  42546. const { textureDescriptorGPU } = textureData;
  42547. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  42548. return;
  42549. // transfer texture data
  42550. if ( texture.isDataTexture ) {
  42551. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42552. } else if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  42553. for ( let i = 0; i < options.image.depth; i ++ ) {
  42554. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  42555. }
  42556. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  42557. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  42558. } else if ( texture.isCubeTexture ) {
  42559. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY );
  42560. } else if ( texture.isVideoTexture ) {
  42561. const video = texture.source.data;
  42562. textureData.externalTexture = video;
  42563. } else {
  42564. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  42565. }
  42566. //
  42567. textureData.version = texture.version;
  42568. if ( texture.onUpdate ) texture.onUpdate( texture );
  42569. }
  42570. /**
  42571. * Returns texture data as a typed array.
  42572. *
  42573. * @async
  42574. * @param {Texture} texture - The texture to copy.
  42575. * @param {Number} x - The x coordinate of the copy origin.
  42576. * @param {Number} y - The y coordinate of the copy origin.
  42577. * @param {Number} width - The width of the copy.
  42578. * @param {Number} height - The height of the copy.
  42579. * @param {Number} faceIndex - The face index.
  42580. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42581. */
  42582. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42583. const device = this.backend.device;
  42584. const textureData = this.backend.get( texture );
  42585. const textureGPU = textureData.texture;
  42586. const format = textureData.textureDescriptorGPU.format;
  42587. const bytesPerTexel = this._getBytesPerTexel( format );
  42588. let bytesPerRow = width * bytesPerTexel;
  42589. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  42590. const readBuffer = device.createBuffer(
  42591. {
  42592. size: width * height * bytesPerTexel,
  42593. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  42594. }
  42595. );
  42596. const encoder = device.createCommandEncoder();
  42597. encoder.copyTextureToBuffer(
  42598. {
  42599. texture: textureGPU,
  42600. origin: { x, y, z: faceIndex },
  42601. },
  42602. {
  42603. buffer: readBuffer,
  42604. bytesPerRow: bytesPerRow
  42605. },
  42606. {
  42607. width: width,
  42608. height: height
  42609. }
  42610. );
  42611. const typedArrayType = this._getTypedArrayType( format );
  42612. device.queue.submit( [ encoder.finish() ] );
  42613. await readBuffer.mapAsync( GPUMapMode.READ );
  42614. const buffer = readBuffer.getMappedRange();
  42615. return new typedArrayType( buffer );
  42616. }
  42617. /**
  42618. * Returns `true` if the given texture is an environment map.
  42619. *
  42620. * @private
  42621. * @param {Texture} texture - The texture.
  42622. * @return {Boolean} Whether the given texture is an environment map or not.
  42623. */
  42624. _isEnvironmentTexture( texture ) {
  42625. const mapping = texture.mapping;
  42626. return ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) || ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  42627. }
  42628. /**
  42629. * Returns the default GPU texture for the given format.
  42630. *
  42631. * @private
  42632. * @param {String} format - The GPU format.
  42633. * @return {GPUTexture} The GPU texture.
  42634. */
  42635. _getDefaultTextureGPU( format ) {
  42636. let defaultTexture = this.defaultTexture[ format ];
  42637. if ( defaultTexture === undefined ) {
  42638. const texture = new Texture();
  42639. texture.minFilter = NearestFilter;
  42640. texture.magFilter = NearestFilter;
  42641. this.createTexture( texture, { width: 1, height: 1, format } );
  42642. this.defaultTexture[ format ] = defaultTexture = texture;
  42643. }
  42644. return this.backend.get( defaultTexture ).texture;
  42645. }
  42646. /**
  42647. * Returns the default GPU cube texture for the given format.
  42648. *
  42649. * @private
  42650. * @param {String} format - The GPU format.
  42651. * @return {GPUTexture} The GPU texture.
  42652. */
  42653. _getDefaultCubeTextureGPU( format ) {
  42654. let defaultCubeTexture = this.defaultTexture[ format ];
  42655. if ( defaultCubeTexture === undefined ) {
  42656. const texture = new CubeTexture();
  42657. texture.minFilter = NearestFilter;
  42658. texture.magFilter = NearestFilter;
  42659. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  42660. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  42661. }
  42662. return this.backend.get( defaultCubeTexture ).texture;
  42663. }
  42664. /**
  42665. * Returns the default video frame used as default data in context of video textures.
  42666. *
  42667. * @private
  42668. * @return {VideoFrame} The video frame.
  42669. */
  42670. _getDefaultVideoFrame() {
  42671. let defaultVideoFrame = this.defaultVideoFrame;
  42672. if ( defaultVideoFrame === null ) {
  42673. const init = {
  42674. timestamp: 0,
  42675. codedWidth: 1,
  42676. codedHeight: 1,
  42677. format: 'RGBA',
  42678. };
  42679. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  42680. }
  42681. return defaultVideoFrame;
  42682. }
  42683. /**
  42684. * Uploads cube texture image data to the GPU memory.
  42685. *
  42686. * @private
  42687. * @param {Array} images - The cube image data.
  42688. * @param {GPUTexture} textureGPU - The GPU texture.
  42689. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42690. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42691. */
  42692. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY ) {
  42693. for ( let i = 0; i < 6; i ++ ) {
  42694. const image = images[ i ];
  42695. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  42696. if ( image.isDataTexture ) {
  42697. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42698. } else {
  42699. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  42700. }
  42701. }
  42702. }
  42703. /**
  42704. * Uploads texture image data to the GPU memory.
  42705. *
  42706. * @private
  42707. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  42708. * @param {GPUTexture} textureGPU - The GPU texture.
  42709. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42710. * @param {Number} originDepth - The origin depth.
  42711. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42712. */
  42713. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY ) {
  42714. const device = this.backend.device;
  42715. device.queue.copyExternalImageToTexture(
  42716. {
  42717. source: image,
  42718. flipY: flipY
  42719. }, {
  42720. texture: textureGPU,
  42721. mipLevel: 0,
  42722. origin: { x: 0, y: 0, z: originDepth }
  42723. }, {
  42724. width: image.width,
  42725. height: image.height,
  42726. depthOrArrayLayers: 1
  42727. }
  42728. );
  42729. }
  42730. /**
  42731. * Returns the pass utils singleton.
  42732. *
  42733. * @private
  42734. * @return {WebGPUTexturePassUtils} The utils instance.
  42735. */
  42736. _getPassUtils() {
  42737. let passUtils = this._passUtils;
  42738. if ( passUtils === null ) {
  42739. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  42740. }
  42741. return passUtils;
  42742. }
  42743. /**
  42744. * Generates mipmaps for the given GPU texture.
  42745. *
  42746. * @private
  42747. * @param {GPUTexture} textureGPU - The GPU texture object.
  42748. * @param {Object} textureDescriptorGPU - The texture descriptor.
  42749. * @param {Number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  42750. */
  42751. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  42752. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  42753. }
  42754. /**
  42755. * Flip the contents of the given GPU texture along its vertical axis.
  42756. *
  42757. * @private
  42758. * @param {GPUTexture} textureGPU - The GPU texture object.
  42759. * @param {Object} textureDescriptorGPU - The texture descriptor.
  42760. * @param {Number} [originDepth=0] - The origin depth.
  42761. */
  42762. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  42763. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  42764. }
  42765. /**
  42766. * Uploads texture buffer data to the GPU memory.
  42767. *
  42768. * @private
  42769. * @param {Object} image - An object defining the image buffer data.
  42770. * @param {GPUTexture} textureGPU - The GPU texture.
  42771. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42772. * @param {Number} originDepth - The origin depth.
  42773. * @param {Boolean} flipY - Whether to flip texture data along their vertical axis or not.
  42774. * @param {Number} [depth=0] - TODO.
  42775. */
  42776. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  42777. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42778. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  42779. const device = this.backend.device;
  42780. const data = image.data;
  42781. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  42782. const bytesPerRow = image.width * bytesPerTexel;
  42783. device.queue.writeTexture(
  42784. {
  42785. texture: textureGPU,
  42786. mipLevel: 0,
  42787. origin: { x: 0, y: 0, z: originDepth }
  42788. },
  42789. data,
  42790. {
  42791. offset: image.width * image.height * bytesPerTexel * depth,
  42792. bytesPerRow
  42793. },
  42794. {
  42795. width: image.width,
  42796. height: image.height,
  42797. depthOrArrayLayers: 1
  42798. } );
  42799. if ( flipY === true ) {
  42800. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  42801. }
  42802. }
  42803. /**
  42804. * Uploads compressed texture data to the GPU memory.
  42805. *
  42806. * @private
  42807. * @param {Array<Object>} mipmaps - An array with mipmap data.
  42808. * @param {GPUTexture} textureGPU - The GPU texture.
  42809. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  42810. */
  42811. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  42812. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  42813. const device = this.backend.device;
  42814. const blockData = this._getBlockData( textureDescriptorGPU.format );
  42815. const isTextureArray = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  42816. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42817. const mipmap = mipmaps[ i ];
  42818. const width = mipmap.width;
  42819. const height = mipmap.height;
  42820. const depth = isTextureArray ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  42821. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  42822. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  42823. for ( let j = 0; j < depth; j ++ ) {
  42824. device.queue.writeTexture(
  42825. {
  42826. texture: textureGPU,
  42827. mipLevel: i,
  42828. origin: { x: 0, y: 0, z: j }
  42829. },
  42830. mipmap.data,
  42831. {
  42832. offset: j * bytesPerImage,
  42833. bytesPerRow,
  42834. rowsPerImage: Math.ceil( height / blockData.height )
  42835. },
  42836. {
  42837. width: Math.ceil( width / blockData.width ) * blockData.width,
  42838. height: Math.ceil( height / blockData.height ) * blockData.height,
  42839. depthOrArrayLayers: 1
  42840. }
  42841. );
  42842. }
  42843. }
  42844. }
  42845. /**
  42846. * This method is only relevant for compressed texture formats. It returns a block
  42847. * data descriptor for the given GPU compressed texture format.
  42848. *
  42849. * @private
  42850. * @param {String} format - The GPU compressed texture format.
  42851. * @return {Object} The block data descriptor.
  42852. */
  42853. _getBlockData( format ) {
  42854. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  42855. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  42856. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  42857. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSNorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  42858. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  42859. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  42860. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  42861. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42862. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  42863. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42864. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  42865. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  42866. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  42867. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  42868. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  42869. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  42870. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  42871. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  42872. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  42873. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  42874. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  42875. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  42876. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  42877. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  42878. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  42879. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  42880. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  42881. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  42882. }
  42883. /**
  42884. * Converts the three.js uv wrapping constants to GPU address mode constants.
  42885. *
  42886. * @private
  42887. * @param {Number} value - The three.js constant defining a uv wrapping mode.
  42888. * @return {String} The GPU address mode.
  42889. */
  42890. _convertAddressMode( value ) {
  42891. let addressMode = GPUAddressMode.ClampToEdge;
  42892. if ( value === RepeatWrapping ) {
  42893. addressMode = GPUAddressMode.Repeat;
  42894. } else if ( value === MirroredRepeatWrapping ) {
  42895. addressMode = GPUAddressMode.MirrorRepeat;
  42896. }
  42897. return addressMode;
  42898. }
  42899. /**
  42900. * Converts the three.js filter constants to GPU filter constants.
  42901. *
  42902. * @private
  42903. * @param {Number} value - The three.js constant defining a filter mode.
  42904. * @return {String} The GPU filter mode.
  42905. */
  42906. _convertFilterMode( value ) {
  42907. let filterMode = GPUFilterMode.Linear;
  42908. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  42909. filterMode = GPUFilterMode.Nearest;
  42910. }
  42911. return filterMode;
  42912. }
  42913. /**
  42914. * Returns the bytes-per-texel value for the given GPU texture format.
  42915. *
  42916. * @private
  42917. * @param {String} format - The GPU texture format.
  42918. * @return {Number} The bytes-per-texel.
  42919. */
  42920. _getBytesPerTexel( format ) {
  42921. // 8-bit formats
  42922. if ( format === GPUTextureFormat.R8Unorm ||
  42923. format === GPUTextureFormat.R8Snorm ||
  42924. format === GPUTextureFormat.R8Uint ||
  42925. format === GPUTextureFormat.R8Sint ) return 1;
  42926. // 16-bit formats
  42927. if ( format === GPUTextureFormat.R16Uint ||
  42928. format === GPUTextureFormat.R16Sint ||
  42929. format === GPUTextureFormat.R16Float ||
  42930. format === GPUTextureFormat.RG8Unorm ||
  42931. format === GPUTextureFormat.RG8Snorm ||
  42932. format === GPUTextureFormat.RG8Uint ||
  42933. format === GPUTextureFormat.RG8Sint ) return 2;
  42934. // 32-bit formats
  42935. if ( format === GPUTextureFormat.R32Uint ||
  42936. format === GPUTextureFormat.R32Sint ||
  42937. format === GPUTextureFormat.R32Float ||
  42938. format === GPUTextureFormat.RG16Uint ||
  42939. format === GPUTextureFormat.RG16Sint ||
  42940. format === GPUTextureFormat.RG16Float ||
  42941. format === GPUTextureFormat.RGBA8Unorm ||
  42942. format === GPUTextureFormat.RGBA8UnormSRGB ||
  42943. format === GPUTextureFormat.RGBA8Snorm ||
  42944. format === GPUTextureFormat.RGBA8Uint ||
  42945. format === GPUTextureFormat.RGBA8Sint ||
  42946. format === GPUTextureFormat.BGRA8Unorm ||
  42947. format === GPUTextureFormat.BGRA8UnormSRGB ||
  42948. // Packed 32-bit formats
  42949. format === GPUTextureFormat.RGB9E5UFloat ||
  42950. format === GPUTextureFormat.RGB10A2Unorm ||
  42951. format === GPUTextureFormat.RG11B10UFloat ||
  42952. format === GPUTextureFormat.Depth32Float ||
  42953. format === GPUTextureFormat.Depth24Plus ||
  42954. format === GPUTextureFormat.Depth24PlusStencil8 ||
  42955. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  42956. // 64-bit formats
  42957. if ( format === GPUTextureFormat.RG32Uint ||
  42958. format === GPUTextureFormat.RG32Sint ||
  42959. format === GPUTextureFormat.RG32Float ||
  42960. format === GPUTextureFormat.RGBA16Uint ||
  42961. format === GPUTextureFormat.RGBA16Sint ||
  42962. format === GPUTextureFormat.RGBA16Float ) return 8;
  42963. // 128-bit formats
  42964. if ( format === GPUTextureFormat.RGBA32Uint ||
  42965. format === GPUTextureFormat.RGBA32Sint ||
  42966. format === GPUTextureFormat.RGBA32Float ) return 16;
  42967. }
  42968. /**
  42969. * Returns the corresponding typed array type for the given GPU texture format.
  42970. *
  42971. * @private
  42972. * @param {String} format - The GPU texture format.
  42973. * @return {TypedArray.constructor} The typed array type.
  42974. */
  42975. _getTypedArrayType( format ) {
  42976. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  42977. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  42978. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  42979. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  42980. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  42981. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  42982. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  42983. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  42984. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  42985. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  42986. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  42987. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  42988. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  42989. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  42990. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  42991. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  42992. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  42993. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  42994. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  42995. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  42996. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  42997. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  42998. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  42999. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  43000. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  43001. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  43002. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  43003. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  43004. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  43005. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  43006. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  43007. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  43008. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  43009. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  43010. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  43011. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  43012. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  43013. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  43014. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  43015. }
  43016. /**
  43017. * Returns the GPU dimensions for the given texture.
  43018. *
  43019. * @private
  43020. * @param {Texture} texture - The texture.
  43021. * @return {String} The GPU dimension.
  43022. */
  43023. _getDimension( texture ) {
  43024. let dimension;
  43025. if ( texture.isData3DTexture ) {
  43026. dimension = GPUTextureDimension.ThreeD;
  43027. } else {
  43028. dimension = GPUTextureDimension.TwoD;
  43029. }
  43030. return dimension;
  43031. }
  43032. }
  43033. /**
  43034. * Returns the GPU format for the given texture.
  43035. *
  43036. * @param {Texture} texture - The texture.
  43037. * @param {GPUDevice?} [device=null] - The GPU device which is used for feature detection.
  43038. * It is not necessary to apply the device for most formats.
  43039. * @return {String} The GPU format.
  43040. */
  43041. function getFormat( texture, device = null ) {
  43042. const format = texture.format;
  43043. const type = texture.type;
  43044. const colorSpace = texture.colorSpace;
  43045. let formatGPU;
  43046. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  43047. switch ( format ) {
  43048. case RGBA_S3TC_DXT1_Format:
  43049. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  43050. break;
  43051. case RGBA_S3TC_DXT3_Format:
  43052. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  43053. break;
  43054. case RGBA_S3TC_DXT5_Format:
  43055. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  43056. break;
  43057. case RGB_ETC2_Format:
  43058. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  43059. break;
  43060. case RGBA_ETC2_EAC_Format:
  43061. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  43062. break;
  43063. case RGBA_ASTC_4x4_Format:
  43064. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  43065. break;
  43066. case RGBA_ASTC_5x4_Format:
  43067. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  43068. break;
  43069. case RGBA_ASTC_5x5_Format:
  43070. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  43071. break;
  43072. case RGBA_ASTC_6x5_Format:
  43073. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  43074. break;
  43075. case RGBA_ASTC_6x6_Format:
  43076. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  43077. break;
  43078. case RGBA_ASTC_8x5_Format:
  43079. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  43080. break;
  43081. case RGBA_ASTC_8x6_Format:
  43082. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  43083. break;
  43084. case RGBA_ASTC_8x8_Format:
  43085. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  43086. break;
  43087. case RGBA_ASTC_10x5_Format:
  43088. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  43089. break;
  43090. case RGBA_ASTC_10x6_Format:
  43091. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  43092. break;
  43093. case RGBA_ASTC_10x8_Format:
  43094. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  43095. break;
  43096. case RGBA_ASTC_10x10_Format:
  43097. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  43098. break;
  43099. case RGBA_ASTC_12x10_Format:
  43100. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  43101. break;
  43102. case RGBA_ASTC_12x12_Format:
  43103. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  43104. break;
  43105. case RGBAFormat:
  43106. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43107. break;
  43108. default:
  43109. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43110. }
  43111. } else {
  43112. switch ( format ) {
  43113. case RGBAFormat:
  43114. switch ( type ) {
  43115. case ByteType:
  43116. formatGPU = GPUTextureFormat.RGBA8Snorm;
  43117. break;
  43118. case ShortType:
  43119. formatGPU = GPUTextureFormat.RGBA16Sint;
  43120. break;
  43121. case UnsignedShortType:
  43122. formatGPU = GPUTextureFormat.RGBA16Uint;
  43123. break;
  43124. case UnsignedIntType:
  43125. formatGPU = GPUTextureFormat.RGBA32Uint;
  43126. break;
  43127. case IntType:
  43128. formatGPU = GPUTextureFormat.RGBA32Sint;
  43129. break;
  43130. case UnsignedByteType:
  43131. formatGPU = ( colorSpace === SRGBColorSpace ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  43132. break;
  43133. case HalfFloatType:
  43134. formatGPU = GPUTextureFormat.RGBA16Float;
  43135. break;
  43136. case FloatType:
  43137. formatGPU = GPUTextureFormat.RGBA32Float;
  43138. break;
  43139. default:
  43140. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  43141. }
  43142. break;
  43143. case RGBFormat:
  43144. switch ( type ) {
  43145. case UnsignedInt5999Type:
  43146. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  43147. break;
  43148. default:
  43149. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  43150. }
  43151. break;
  43152. case RedFormat:
  43153. switch ( type ) {
  43154. case ByteType:
  43155. formatGPU = GPUTextureFormat.R8Snorm;
  43156. break;
  43157. case ShortType:
  43158. formatGPU = GPUTextureFormat.R16Sint;
  43159. break;
  43160. case UnsignedShortType:
  43161. formatGPU = GPUTextureFormat.R16Uint;
  43162. break;
  43163. case UnsignedIntType:
  43164. formatGPU = GPUTextureFormat.R32Uint;
  43165. break;
  43166. case IntType:
  43167. formatGPU = GPUTextureFormat.R32Sint;
  43168. break;
  43169. case UnsignedByteType:
  43170. formatGPU = GPUTextureFormat.R8Unorm;
  43171. break;
  43172. case HalfFloatType:
  43173. formatGPU = GPUTextureFormat.R16Float;
  43174. break;
  43175. case FloatType:
  43176. formatGPU = GPUTextureFormat.R32Float;
  43177. break;
  43178. default:
  43179. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  43180. }
  43181. break;
  43182. case RGFormat:
  43183. switch ( type ) {
  43184. case ByteType:
  43185. formatGPU = GPUTextureFormat.RG8Snorm;
  43186. break;
  43187. case ShortType:
  43188. formatGPU = GPUTextureFormat.RG16Sint;
  43189. break;
  43190. case UnsignedShortType:
  43191. formatGPU = GPUTextureFormat.RG16Uint;
  43192. break;
  43193. case UnsignedIntType:
  43194. formatGPU = GPUTextureFormat.RG32Uint;
  43195. break;
  43196. case IntType:
  43197. formatGPU = GPUTextureFormat.RG32Sint;
  43198. break;
  43199. case UnsignedByteType:
  43200. formatGPU = GPUTextureFormat.RG8Unorm;
  43201. break;
  43202. case HalfFloatType:
  43203. formatGPU = GPUTextureFormat.RG16Float;
  43204. break;
  43205. case FloatType:
  43206. formatGPU = GPUTextureFormat.RG32Float;
  43207. break;
  43208. default:
  43209. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  43210. }
  43211. break;
  43212. case DepthFormat:
  43213. switch ( type ) {
  43214. case UnsignedShortType:
  43215. formatGPU = GPUTextureFormat.Depth16Unorm;
  43216. break;
  43217. case UnsignedIntType:
  43218. formatGPU = GPUTextureFormat.Depth24Plus;
  43219. break;
  43220. case FloatType:
  43221. formatGPU = GPUTextureFormat.Depth32Float;
  43222. break;
  43223. default:
  43224. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  43225. }
  43226. break;
  43227. case DepthStencilFormat:
  43228. switch ( type ) {
  43229. case UnsignedInt248Type:
  43230. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  43231. break;
  43232. case FloatType:
  43233. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  43234. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  43235. }
  43236. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  43237. break;
  43238. default:
  43239. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  43240. }
  43241. break;
  43242. case RedIntegerFormat:
  43243. switch ( type ) {
  43244. case IntType:
  43245. formatGPU = GPUTextureFormat.R32Sint;
  43246. break;
  43247. case UnsignedIntType:
  43248. formatGPU = GPUTextureFormat.R32Uint;
  43249. break;
  43250. default:
  43251. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  43252. }
  43253. break;
  43254. case RGIntegerFormat:
  43255. switch ( type ) {
  43256. case IntType:
  43257. formatGPU = GPUTextureFormat.RG32Sint;
  43258. break;
  43259. case UnsignedIntType:
  43260. formatGPU = GPUTextureFormat.RG32Uint;
  43261. break;
  43262. default:
  43263. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  43264. }
  43265. break;
  43266. case RGBAIntegerFormat:
  43267. switch ( type ) {
  43268. case IntType:
  43269. formatGPU = GPUTextureFormat.RGBA32Sint;
  43270. break;
  43271. case UnsignedIntType:
  43272. formatGPU = GPUTextureFormat.RGBA32Uint;
  43273. break;
  43274. default:
  43275. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  43276. }
  43277. break;
  43278. default:
  43279. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  43280. }
  43281. }
  43282. return formatGPU;
  43283. }
  43284. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  43285. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  43286. const wgslTypeLib$1 = {
  43287. 'f32': 'float',
  43288. 'i32': 'int',
  43289. 'u32': 'uint',
  43290. 'bool': 'bool',
  43291. 'vec2<f32>': 'vec2',
  43292. 'vec2<i32>': 'ivec2',
  43293. 'vec2<u32>': 'uvec2',
  43294. 'vec2<bool>': 'bvec2',
  43295. 'vec2f': 'vec2',
  43296. 'vec2i': 'ivec2',
  43297. 'vec2u': 'uvec2',
  43298. 'vec2b': 'bvec2',
  43299. 'vec3<f32>': 'vec3',
  43300. 'vec3<i32>': 'ivec3',
  43301. 'vec3<u32>': 'uvec3',
  43302. 'vec3<bool>': 'bvec3',
  43303. 'vec3f': 'vec3',
  43304. 'vec3i': 'ivec3',
  43305. 'vec3u': 'uvec3',
  43306. 'vec3b': 'bvec3',
  43307. 'vec4<f32>': 'vec4',
  43308. 'vec4<i32>': 'ivec4',
  43309. 'vec4<u32>': 'uvec4',
  43310. 'vec4<bool>': 'bvec4',
  43311. 'vec4f': 'vec4',
  43312. 'vec4i': 'ivec4',
  43313. 'vec4u': 'uvec4',
  43314. 'vec4b': 'bvec4',
  43315. 'mat2x2<f32>': 'mat2',
  43316. 'mat2x2f': 'mat2',
  43317. 'mat3x3<f32>': 'mat3',
  43318. 'mat3x3f': 'mat3',
  43319. 'mat4x4<f32>': 'mat4',
  43320. 'mat4x4f': 'mat4',
  43321. 'sampler': 'sampler',
  43322. 'texture_1d': 'texture',
  43323. 'texture_2d': 'texture',
  43324. 'texture_2d_array': 'texture',
  43325. 'texture_multisampled_2d': 'cubeTexture',
  43326. 'texture_depth_2d': 'depthTexture',
  43327. 'texture_depth_multisampled_2d': 'depthTexture',
  43328. 'texture_3d': 'texture3D',
  43329. 'texture_cube': 'cubeTexture',
  43330. 'texture_cube_array': 'cubeTexture',
  43331. 'texture_storage_1d': 'storageTexture',
  43332. 'texture_storage_2d': 'storageTexture',
  43333. 'texture_storage_2d_array': 'storageTexture',
  43334. 'texture_storage_3d': 'storageTexture'
  43335. };
  43336. const parse = ( source ) => {
  43337. source = source.trim();
  43338. const declaration = source.match( declarationRegexp );
  43339. if ( declaration !== null && declaration.length === 4 ) {
  43340. const inputsCode = declaration[ 2 ];
  43341. const propsMatches = [];
  43342. let match = null;
  43343. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  43344. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  43345. }
  43346. // Process matches to correctly pair names and types
  43347. const inputs = [];
  43348. for ( let i = 0; i < propsMatches.length; i ++ ) {
  43349. const { name, type } = propsMatches[ i ];
  43350. let resolvedType = type;
  43351. if ( resolvedType.startsWith( 'ptr' ) ) {
  43352. resolvedType = 'pointer';
  43353. } else {
  43354. if ( resolvedType.startsWith( 'texture' ) ) {
  43355. resolvedType = type.split( '<' )[ 0 ];
  43356. }
  43357. resolvedType = wgslTypeLib$1[ resolvedType ];
  43358. }
  43359. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  43360. }
  43361. const blockCode = source.substring( declaration[ 0 ].length );
  43362. const outputType = declaration[ 3 ] || 'void';
  43363. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  43364. const type = wgslTypeLib$1[ outputType ] || outputType;
  43365. return {
  43366. type,
  43367. inputs,
  43368. name,
  43369. inputsCode,
  43370. blockCode,
  43371. outputType
  43372. };
  43373. } else {
  43374. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  43375. }
  43376. };
  43377. /**
  43378. * This class represents a WSL node function.
  43379. *
  43380. * @augments NodeFunction
  43381. */
  43382. class WGSLNodeFunction extends NodeFunction {
  43383. /**
  43384. * Constructs a new WGSL node function.
  43385. *
  43386. * @param {String} source - The WGSL source.
  43387. */
  43388. constructor( source ) {
  43389. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  43390. super( type, inputs, name );
  43391. this.inputsCode = inputsCode;
  43392. this.blockCode = blockCode;
  43393. this.outputType = outputType;
  43394. }
  43395. /**
  43396. * This method returns the WGSL code of the node function.
  43397. *
  43398. * @param {String} [name=this.name] - The function's name.
  43399. * @return {String} The shader code.
  43400. */
  43401. getCode( name = this.name ) {
  43402. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  43403. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  43404. }
  43405. }
  43406. /**
  43407. * A WGSL node parser.
  43408. *
  43409. * @augments NodeParser
  43410. */
  43411. class WGSLNodeParser extends NodeParser {
  43412. /**
  43413. * The method parses the given WGSL code an returns a node function.
  43414. *
  43415. * @param {String} source - The WGSL code.
  43416. * @return {WGSLNodeFunction} A node function.
  43417. */
  43418. parseFunction( source ) {
  43419. return new WGSLNodeFunction( source );
  43420. }
  43421. }
  43422. // GPUShaderStage is not defined in browsers not supporting WebGPU
  43423. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  43424. const accessNames = {
  43425. [ NodeAccess.READ_ONLY ]: 'read',
  43426. [ NodeAccess.WRITE_ONLY ]: 'write',
  43427. [ NodeAccess.READ_WRITE ]: 'read_write'
  43428. };
  43429. const wrapNames = {
  43430. [ RepeatWrapping ]: 'repeat',
  43431. [ ClampToEdgeWrapping ]: 'clamp',
  43432. [ MirroredRepeatWrapping ]: 'mirror'
  43433. };
  43434. const gpuShaderStageLib = {
  43435. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  43436. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  43437. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  43438. };
  43439. const supports = {
  43440. instance: true,
  43441. swizzleAssign: false,
  43442. storageBuffer: true
  43443. };
  43444. const wgslFnOpLib = {
  43445. '^^': 'tsl_xor'
  43446. };
  43447. const wgslTypeLib = {
  43448. float: 'f32',
  43449. int: 'i32',
  43450. uint: 'u32',
  43451. bool: 'bool',
  43452. color: 'vec3<f32>',
  43453. vec2: 'vec2<f32>',
  43454. ivec2: 'vec2<i32>',
  43455. uvec2: 'vec2<u32>',
  43456. bvec2: 'vec2<bool>',
  43457. vec3: 'vec3<f32>',
  43458. ivec3: 'vec3<i32>',
  43459. uvec3: 'vec3<u32>',
  43460. bvec3: 'vec3<bool>',
  43461. vec4: 'vec4<f32>',
  43462. ivec4: 'vec4<i32>',
  43463. uvec4: 'vec4<u32>',
  43464. bvec4: 'vec4<bool>',
  43465. mat2: 'mat2x2<f32>',
  43466. mat3: 'mat3x3<f32>',
  43467. mat4: 'mat4x4<f32>'
  43468. };
  43469. const wgslCodeCache = {};
  43470. const wgslPolyfill = {
  43471. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  43472. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  43473. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  43474. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  43475. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  43476. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  43477. 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 ); }' ),
  43478. 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 ); }' ),
  43479. 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 ); }' ),
  43480. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  43481. 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 ); }' ),
  43482. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  43483. biquadraticTexture: new CodeNode( /* wgsl */`
  43484. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  43485. let res = vec2f( iRes );
  43486. let uvScaled = coord * res;
  43487. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  43488. // https://www.shadertoy.com/view/WtyXRy
  43489. let uv = uvWrapping - 0.5;
  43490. let iuv = floor( uv );
  43491. let f = fract( uv );
  43492. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  43493. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  43494. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  43495. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  43496. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  43497. }
  43498. ` )
  43499. };
  43500. const wgslMethods = {
  43501. dFdx: 'dpdx',
  43502. dFdy: '- dpdy',
  43503. mod_float: 'tsl_mod_float',
  43504. mod_vec2: 'tsl_mod_vec2',
  43505. mod_vec3: 'tsl_mod_vec3',
  43506. mod_vec4: 'tsl_mod_vec4',
  43507. equals_bool: 'tsl_equals_bool',
  43508. equals_bvec2: 'tsl_equals_bvec2',
  43509. equals_bvec3: 'tsl_equals_bvec3',
  43510. equals_bvec4: 'tsl_equals_bvec4',
  43511. inversesqrt: 'inverseSqrt',
  43512. bitcast: 'bitcast<f32>'
  43513. };
  43514. // WebGPU issue: does not support pow() with negative base on Windows
  43515. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  43516. 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 ); }' );
  43517. 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 ] );
  43518. 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 ] );
  43519. 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 ] );
  43520. wgslMethods.pow_float = 'tsl_pow_float';
  43521. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  43522. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  43523. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  43524. }
  43525. //
  43526. let diagnostics = '';
  43527. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  43528. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  43529. }
  43530. /**
  43531. * A node builder targeting WGSL.
  43532. *
  43533. * This module generates WGSL shader code from node materials and also
  43534. * generates the respective bindings and vertex buffer definitions. These
  43535. * data are later used by the renderer to create render and compute pipelines
  43536. * for render objects.
  43537. *
  43538. * @augments NodeBuilder
  43539. */
  43540. class WGSLNodeBuilder extends NodeBuilder {
  43541. /**
  43542. * Constructs a new WGSL node builder renderer.
  43543. *
  43544. * @param {Object3D} object - The 3D object.
  43545. * @param {Renderer} renderer - The renderer.
  43546. */
  43547. constructor( object, renderer ) {
  43548. super( object, renderer, new WGSLNodeParser() );
  43549. /**
  43550. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  43551. * another dictionary which manages UBOs per group ('render','frame','object').
  43552. *
  43553. * @type {Object<String,Object<String,NodeUniformsGroup>>}
  43554. */
  43555. this.uniformGroups = {};
  43556. /**
  43557. * A dictionary that holds for each shader stage a Map of builtins.
  43558. *
  43559. * @type {Object<String,Map<String,Object>>}
  43560. */
  43561. this.builtins = {};
  43562. /**
  43563. * A dictionary that holds for each shader stage a Set of directives.
  43564. *
  43565. * @type {Object<String,Set<String>>}
  43566. */
  43567. this.directives = {};
  43568. /**
  43569. * A map for managing scope arrays. Only relevant for when using
  43570. * {@link module:WorkgroupInfoNode} in context of compute shaders.
  43571. *
  43572. * @type {Map<String,Object>}
  43573. */
  43574. this.scopedArrays = new Map();
  43575. }
  43576. /**
  43577. * Checks if the given texture requires a manual conversion to the working color space.
  43578. *
  43579. * @param {Texture} texture - The texture to check.
  43580. * @return {Boolean} Whether the given texture requires a conversion to working color space or not.
  43581. */
  43582. needsToWorkingColorSpace( texture ) {
  43583. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  43584. }
  43585. /**
  43586. * Generates the WGSL snippet for sampled textures.
  43587. *
  43588. * @private
  43589. * @param {Texture} texture - The texture.
  43590. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43591. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43592. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43593. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43594. * @return {String} The WGSL snippet.
  43595. */
  43596. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43597. if ( shaderStage === 'fragment' ) {
  43598. if ( depthSnippet ) {
  43599. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  43600. } else {
  43601. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  43602. }
  43603. } else if ( this.isFilteredTexture( texture ) ) {
  43604. return this.generateFilteredTexture( texture, textureProperty, uvSnippet );
  43605. } else {
  43606. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0' );
  43607. }
  43608. }
  43609. /**
  43610. * Generates the WGSL snippet when sampling video textures.
  43611. *
  43612. * @private
  43613. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  43614. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43615. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43616. * @return {String} The WGSL snippet.
  43617. */
  43618. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  43619. if ( shaderStage === 'fragment' ) {
  43620. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  43621. } else {
  43622. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  43623. }
  43624. }
  43625. /**
  43626. * Generates the WGSL snippet when sampling textures with explicit mip level.
  43627. *
  43628. * @private
  43629. * @param {Texture} texture - The texture.
  43630. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43631. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43632. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43633. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43634. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43635. * @return {String} The WGSL snippet.
  43636. */
  43637. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43638. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false ) {
  43639. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  43640. } else if ( this.isFilteredTexture( texture ) ) {
  43641. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  43642. } else {
  43643. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  43644. }
  43645. }
  43646. /**
  43647. * Generates a wrap function used in context of textures.
  43648. *
  43649. * @param {Texture} texture - The texture to generate the function for.
  43650. * @return {String} The name of the generated function.
  43651. */
  43652. generateWrapFunction( texture ) {
  43653. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${texture.isData3DTexture ? '3d' : '2d'}T`;
  43654. let nodeCode = wgslCodeCache[ functionName ];
  43655. if ( nodeCode === undefined ) {
  43656. const includes = [];
  43657. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  43658. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  43659. let code = `fn ${functionName}( coord : ${coordType} ) -> ${coordType} {\n\n\treturn ${coordType}(\n`;
  43660. const addWrapSnippet = ( wrap, axis ) => {
  43661. if ( wrap === RepeatWrapping ) {
  43662. includes.push( wgslPolyfill.repeatWrapping_float );
  43663. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  43664. } else if ( wrap === ClampToEdgeWrapping ) {
  43665. includes.push( wgslPolyfill.clampWrapping_float );
  43666. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  43667. } else if ( wrap === MirroredRepeatWrapping ) {
  43668. includes.push( wgslPolyfill.mirrorWrapping_float );
  43669. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  43670. } else {
  43671. code += `\t\tcoord.${ axis }`;
  43672. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  43673. }
  43674. };
  43675. addWrapSnippet( texture.wrapS, 'x' );
  43676. code += ',\n';
  43677. addWrapSnippet( texture.wrapT, 'y' );
  43678. if ( texture.isData3DTexture ) {
  43679. code += ',\n';
  43680. addWrapSnippet( texture.wrapR, 'z' );
  43681. }
  43682. code += '\n\t);\n\n}\n';
  43683. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  43684. }
  43685. nodeCode.build( this );
  43686. return functionName;
  43687. }
  43688. /**
  43689. * Generates a WGSL variable that holds the texture dimension of the given texture.
  43690. * It also returns information about the the number of layers (elements) of an arrayed
  43691. * texture as well as the cube face count of cube textures.
  43692. *
  43693. * @param {Texture} texture - The texture to generate the function for.
  43694. * @param {String} textureProperty - The name of the video texture uniform in the shader.
  43695. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43696. * @return {String} The name of the dimension variable.
  43697. */
  43698. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  43699. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  43700. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  43701. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  43702. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  43703. let textureDimensionsParams;
  43704. let dimensionType;
  43705. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  43706. const isMultisampled = primarySamples > 1;
  43707. if ( texture.isData3DTexture ) {
  43708. dimensionType = 'vec3<u32>';
  43709. } else {
  43710. // Regular 2D textures, depth textures, etc.
  43711. dimensionType = 'vec2<u32>';
  43712. }
  43713. // Build parameters string based on texture type and multisampling
  43714. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  43715. textureDimensionsParams = textureProperty;
  43716. } else {
  43717. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  43718. }
  43719. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  43720. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  43721. if ( texture.isDataArrayTexture || texture.isData3DTexture ) {
  43722. textureData.arrayLayerCount = new VarNode(
  43723. new ExpressionNode(
  43724. `textureNumLayers(${textureProperty})`,
  43725. 'u32'
  43726. )
  43727. );
  43728. }
  43729. // For cube textures, we know it's always 6 faces
  43730. if ( texture.isTextureCube ) {
  43731. textureData.cubeFaceCount = new VarNode(
  43732. new ExpressionNode( '6u', 'u32' )
  43733. );
  43734. }
  43735. }
  43736. return textureDimensionNode.build( this );
  43737. }
  43738. /**
  43739. * Generates the WGSL snippet for a manual filtered texture.
  43740. *
  43741. * @param {Texture} texture - The texture.
  43742. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43743. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43744. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43745. * @return {String} The WGSL snippet.
  43746. */
  43747. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  43748. this._include( 'biquadraticTexture' );
  43749. const wrapFunction = this.generateWrapFunction( texture );
  43750. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  43751. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  43752. }
  43753. /**
  43754. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  43755. * Since it's a lookup, no sampling or filtering is applied.
  43756. *
  43757. * @param {Texture} texture - The texture.
  43758. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43759. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43760. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43761. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43762. * @return {String} The WGSL snippet.
  43763. */
  43764. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  43765. const wrapFunction = this.generateWrapFunction( texture );
  43766. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  43767. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  43768. const coordSnippet = `${vecType}<u32>(${wrapFunction}(${uvSnippet}) * ${vecType}<f32>(${textureDimension}))`;
  43769. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  43770. }
  43771. /**
  43772. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  43773. *
  43774. * @param {Texture} texture - The texture.
  43775. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43776. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43777. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43778. * @param {String} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43779. * @return {String} The WGSL snippet.
  43780. */
  43781. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  43782. if ( texture.isVideoTexture === true || texture.isStorageTexture === true ) {
  43783. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  43784. } else if ( depthSnippet ) {
  43785. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  43786. } else {
  43787. return `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  43788. }
  43789. }
  43790. /**
  43791. * Generates the WGSL snippet that writes a single texel to a texture.
  43792. *
  43793. * @param {Texture} texture - The texture.
  43794. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43795. * @param {String} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43796. * @param {String} valueSnippet - A WGSL snippet that represent the new texel value.
  43797. * @return {String} The WGSL snippet.
  43798. */
  43799. generateTextureStore( texture, textureProperty, uvIndexSnippet, valueSnippet ) {
  43800. return `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  43801. }
  43802. /**
  43803. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  43804. *
  43805. * @param {Texture} texture - The texture.
  43806. * @return {Boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  43807. */
  43808. isSampleCompare( texture ) {
  43809. return texture.isDepthTexture === true && texture.compareFunction !== null;
  43810. }
  43811. /**
  43812. * Returns `true` if the given texture is unfilterable.
  43813. *
  43814. * @param {Texture} texture - The texture.
  43815. * @return {Boolean} Whether the given texture is unfilterable or not.
  43816. */
  43817. isUnfilterable( texture ) {
  43818. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  43819. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  43820. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  43821. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  43822. }
  43823. /**
  43824. * Generates the WGSL snippet for sampling/loading the given texture.
  43825. *
  43826. * @param {Texture} texture - The texture.
  43827. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43828. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43829. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43830. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43831. * @return {String} The WGSL snippet.
  43832. */
  43833. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43834. let snippet = null;
  43835. if ( texture.isVideoTexture === true ) {
  43836. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43837. } else if ( this.isUnfilterable( texture ) ) {
  43838. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  43839. } else {
  43840. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  43841. }
  43842. return snippet;
  43843. }
  43844. /**
  43845. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  43846. *
  43847. * @param {Texture} texture - The texture.
  43848. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43849. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43850. * @param {Array<String>} gradSnippet - An array holding both gradient WGSL snippets.
  43851. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43852. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43853. * @return {String} The WGSL snippet.
  43854. */
  43855. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43856. if ( shaderStage === 'fragment' ) {
  43857. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  43858. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  43859. } else {
  43860. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  43861. }
  43862. }
  43863. /**
  43864. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  43865. * against a reference value.
  43866. *
  43867. * @param {Texture} texture - The texture.
  43868. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43869. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43870. * @param {String} compareSnippet - A WGSL snippet that represents the reference value.
  43871. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43872. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43873. * @return {String} The WGSL snippet.
  43874. */
  43875. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43876. if ( shaderStage === 'fragment' ) {
  43877. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  43878. } else {
  43879. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  43880. }
  43881. }
  43882. /**
  43883. * Generates the WGSL snippet when sampling textures with explicit mip level.
  43884. *
  43885. * @param {Texture} texture - The texture.
  43886. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43887. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43888. * @param {String} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  43889. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43890. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43891. * @return {String} The WGSL snippet.
  43892. */
  43893. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43894. let snippet = null;
  43895. if ( texture.isVideoTexture === true ) {
  43896. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  43897. } else {
  43898. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage );
  43899. }
  43900. return snippet;
  43901. }
  43902. /**
  43903. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  43904. *
  43905. * @param {Texture} texture - The texture.
  43906. * @param {String} textureProperty - The name of the texture uniform in the shader.
  43907. * @param {String} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  43908. * @param {String} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  43909. * @param {String?} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  43910. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43911. * @return {String} The WGSL snippet.
  43912. */
  43913. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  43914. if ( shaderStage === 'fragment' ) {
  43915. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  43916. } else {
  43917. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  43918. }
  43919. }
  43920. /**
  43921. * Returns a WGSL snippet that represents the property name of the given node.
  43922. *
  43923. * @param {Node} node - The node.
  43924. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  43925. * @return {String} The property name.
  43926. */
  43927. getPropertyName( node, shaderStage = this.shaderStage ) {
  43928. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  43929. if ( shaderStage === 'vertex' ) {
  43930. return `varyings.${ node.name }`;
  43931. }
  43932. } else if ( node.isNodeUniform === true ) {
  43933. const name = node.name;
  43934. const type = node.type;
  43935. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  43936. return name;
  43937. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  43938. return `NodeBuffer_${ node.id }.${name}`;
  43939. } else {
  43940. return node.groupNode.name + '.' + name;
  43941. }
  43942. }
  43943. return super.getPropertyName( node );
  43944. }
  43945. /**
  43946. * Returns the output struct name.
  43947. *
  43948. * @return {String} The name of the output struct.
  43949. */
  43950. getOutputStructName() {
  43951. return 'output';
  43952. }
  43953. /**
  43954. * Returns uniforms group count for the given shader stage.
  43955. *
  43956. * @private
  43957. * @param {String} shaderStage - The shader stage.
  43958. * @return {Number} The uniforms group count for the given shader stage.
  43959. */
  43960. _getUniformGroupCount( shaderStage ) {
  43961. return Object.keys( this.uniforms[ shaderStage ] ).length;
  43962. }
  43963. /**
  43964. * Returns the native shader operator name for a given generic name.
  43965. *
  43966. * @param {String} op - The operator name to resolve.
  43967. * @return {String} The resolved operator name.
  43968. */
  43969. getFunctionOperator( op ) {
  43970. const fnOp = wgslFnOpLib[ op ];
  43971. if ( fnOp !== undefined ) {
  43972. this._include( fnOp );
  43973. return fnOp;
  43974. }
  43975. return null;
  43976. }
  43977. /**
  43978. * Returns the node access for the given node and shader stage.
  43979. *
  43980. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  43981. * @param {String} shaderStage - The shader stage.
  43982. * @return {String} The node access.
  43983. */
  43984. getNodeAccess( node, shaderStage ) {
  43985. if ( shaderStage !== 'compute' )
  43986. return NodeAccess.READ_ONLY;
  43987. return node.access;
  43988. }
  43989. /**
  43990. * Returns A WGSL snippet representing the storage access.
  43991. *
  43992. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  43993. * @param {String} shaderStage - The shader stage.
  43994. * @return {String} The WGSL snippet representing the storage access.
  43995. */
  43996. getStorageAccess( node, shaderStage ) {
  43997. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  43998. }
  43999. /**
  44000. * This method is one of the more important ones since it's responsible
  44001. * for generating a matching binding instance for the given uniform node.
  44002. *
  44003. * These bindings are later used in the renderer to create bind groups
  44004. * and layouts.
  44005. *
  44006. * @param {UniformNode} node - The uniform node.
  44007. * @param {String} type - The node data type.
  44008. * @param {String} shaderStage - The shader stage.
  44009. * @param {String?} [name=null] - An optional uniform name.
  44010. * @return {NodeUniform} The node uniform object.
  44011. */
  44012. getUniformFromNode( node, type, shaderStage, name = null ) {
  44013. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  44014. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  44015. if ( nodeData.uniformGPU === undefined ) {
  44016. let uniformGPU;
  44017. const group = node.groupNode;
  44018. const groupName = group.name;
  44019. const bindings = this.getBindGroupArray( groupName, shaderStage );
  44020. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  44021. let texture = null;
  44022. const access = this.getNodeAccess( node, shaderStage );
  44023. if ( type === 'texture' || type === 'storageTexture' ) {
  44024. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  44025. } else if ( type === 'cubeTexture' ) {
  44026. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  44027. } else if ( type === 'texture3D' ) {
  44028. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  44029. }
  44030. texture.store = node.isStorageTextureNode === true;
  44031. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44032. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( node.value ) === false && texture.store === false ) {
  44033. const sampler = new NodeSampler( `${uniformNode.name}_sampler`, uniformNode.node, group );
  44034. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44035. bindings.push( sampler, texture );
  44036. uniformGPU = [ sampler, texture ];
  44037. } else {
  44038. bindings.push( texture );
  44039. uniformGPU = [ texture ];
  44040. }
  44041. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  44042. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  44043. const buffer = new bufferClass( node, group );
  44044. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44045. bindings.push( buffer );
  44046. uniformGPU = buffer;
  44047. } else {
  44048. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  44049. let uniformsGroup = uniformsStage[ groupName ];
  44050. if ( uniformsGroup === undefined ) {
  44051. uniformsGroup = new NodeUniformsGroup( groupName, group );
  44052. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  44053. uniformsStage[ groupName ] = uniformsGroup;
  44054. bindings.push( uniformsGroup );
  44055. }
  44056. uniformGPU = this.getNodeUniform( uniformNode, type );
  44057. uniformsGroup.addUniform( uniformGPU );
  44058. }
  44059. nodeData.uniformGPU = uniformGPU;
  44060. }
  44061. return uniformNode;
  44062. }
  44063. /**
  44064. * This method should be used whenever builtins are required in nodes.
  44065. * The internal builtins data structure will make sure builtins are
  44066. * defined in the WGSL source.
  44067. *
  44068. * @param {String} name - The builtin name.
  44069. * @param {String} property - The property name.
  44070. * @param {String} type - The node data type.
  44071. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44072. * @return {String} The property name.
  44073. */
  44074. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  44075. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  44076. if ( map.has( name ) === false ) {
  44077. map.set( name, {
  44078. name,
  44079. property,
  44080. type
  44081. } );
  44082. }
  44083. return property;
  44084. }
  44085. /**
  44086. * Returns `true` if the given builtin is defined in the given shader stage.
  44087. *
  44088. * @param {String} name - The builtin name.
  44089. * @param {String} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  44090. * @return {String} Whether the given builtin is defined in the given shader stage or not.
  44091. */
  44092. hasBuiltin( name, shaderStage = this.shaderStage ) {
  44093. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  44094. }
  44095. /**
  44096. * Returns the vertex index builtin.
  44097. *
  44098. * @return {String} The vertex index.
  44099. */
  44100. getVertexIndex() {
  44101. if ( this.shaderStage === 'vertex' ) {
  44102. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  44103. }
  44104. return 'vertexIndex';
  44105. }
  44106. /**
  44107. * Builds the given shader node.
  44108. *
  44109. * @param {ShaderNodeInternal} shaderNode - The shader node.
  44110. * @return {String} The WGSL function code.
  44111. */
  44112. buildFunctionCode( shaderNode ) {
  44113. const layout = shaderNode.layout;
  44114. const flowData = this.flowShaderNode( shaderNode );
  44115. const parameters = [];
  44116. for ( const input of layout.inputs ) {
  44117. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  44118. }
  44119. //
  44120. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  44121. ${ flowData.vars }
  44122. ${ flowData.code }
  44123. `;
  44124. if ( flowData.result ) {
  44125. code += `\treturn ${ flowData.result };\n`;
  44126. }
  44127. code += '\n}\n';
  44128. //
  44129. return code;
  44130. }
  44131. /**
  44132. * Returns the instance index builtin.
  44133. *
  44134. * @return {String} The instance index.
  44135. */
  44136. getInstanceIndex() {
  44137. if ( this.shaderStage === 'vertex' ) {
  44138. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  44139. }
  44140. return 'instanceIndex';
  44141. }
  44142. /**
  44143. * Returns the invocation local index builtin.
  44144. *
  44145. * @return {String} The invocation local index.
  44146. */
  44147. getInvocationLocalIndex() {
  44148. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  44149. }
  44150. /**
  44151. * Returns the subgroup size builtin.
  44152. *
  44153. * @return {String} The subgroup size.
  44154. */
  44155. getSubgroupSize() {
  44156. this.enableSubGroups();
  44157. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44158. }
  44159. /**
  44160. * Returns the invocation subgroup index builtin.
  44161. *
  44162. * @return {String} The invocation subgroup index.
  44163. */
  44164. getInvocationSubgroupIndex() {
  44165. this.enableSubGroups();
  44166. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  44167. }
  44168. /**
  44169. * Returns the subgroup index builtin.
  44170. *
  44171. * @return {String} The subgroup index.
  44172. */
  44173. getSubgroupIndex() {
  44174. this.enableSubGroups();
  44175. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  44176. }
  44177. /**
  44178. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  44179. *
  44180. * @return {null} Null.
  44181. */
  44182. getDrawIndex() {
  44183. return null;
  44184. }
  44185. /**
  44186. * Returns the front facing builtin.
  44187. *
  44188. * @return {String} The front facing builtin.
  44189. */
  44190. getFrontFacing() {
  44191. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  44192. }
  44193. /**
  44194. * Returns the frag coord builtin.
  44195. *
  44196. * @return {String} The frag coord builtin.
  44197. */
  44198. getFragCoord() {
  44199. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  44200. }
  44201. /**
  44202. * Returns the frag depth builtin.
  44203. *
  44204. * @return {String} The frag depth builtin.
  44205. */
  44206. getFragDepth() {
  44207. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  44208. }
  44209. /**
  44210. * Returns the clip distances builtin.
  44211. *
  44212. * @return {String} The clip distances builtin.
  44213. */
  44214. getClipDistance() {
  44215. return 'varyings.hw_clip_distances';
  44216. }
  44217. /**
  44218. * Whether to flip texture data along its vertical axis or not.
  44219. *
  44220. * @return {Boolean} Returns always `false` in context of WGSL.
  44221. */
  44222. isFlipY() {
  44223. return false;
  44224. }
  44225. /**
  44226. * Enables the given directive for the given shader stage.
  44227. *
  44228. * @param {String} name - The directive name.
  44229. * @param {String} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  44230. */
  44231. enableDirective( name, shaderStage = this.shaderStage ) {
  44232. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  44233. stage.add( name );
  44234. }
  44235. /**
  44236. * Returns the directives of the given shader stage as a WGSL string.
  44237. *
  44238. * @param {String} shaderStage - The shader stage.
  44239. * @return {String} A WGSL snippet that enables the directives of the given stage.
  44240. */
  44241. getDirectives( shaderStage ) {
  44242. const snippets = [];
  44243. const directives = this.directives[ shaderStage ];
  44244. if ( directives !== undefined ) {
  44245. for ( const directive of directives ) {
  44246. snippets.push( `enable ${directive};` );
  44247. }
  44248. }
  44249. return snippets.join( '\n' );
  44250. }
  44251. /**
  44252. * Enables the 'subgroups' directive.
  44253. */
  44254. enableSubGroups() {
  44255. this.enableDirective( 'subgroups' );
  44256. }
  44257. /**
  44258. * Enables the 'subgroups-f16' directive.
  44259. */
  44260. enableSubgroupsF16() {
  44261. this.enableDirective( 'subgroups-f16' );
  44262. }
  44263. /**
  44264. * Enables the 'clip_distances' directive.
  44265. */
  44266. enableClipDistances() {
  44267. this.enableDirective( 'clip_distances' );
  44268. }
  44269. /**
  44270. * Enables the 'f16' directive.
  44271. */
  44272. enableShaderF16() {
  44273. this.enableDirective( 'f16' );
  44274. }
  44275. /**
  44276. * Enables the 'dual_source_blending' directive.
  44277. */
  44278. enableDualSourceBlending() {
  44279. this.enableDirective( 'dual_source_blending' );
  44280. }
  44281. /**
  44282. * Enables hardware clipping.
  44283. *
  44284. * @param {String} planeCount - The clipping plane count.
  44285. */
  44286. enableHardwareClipping( planeCount ) {
  44287. this.enableClipDistances();
  44288. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  44289. }
  44290. /**
  44291. * Returns the builtins of the given shader stage as a WGSL string.
  44292. *
  44293. * @param {String} shaderStage - The shader stage.
  44294. * @return {String} A WGSL snippet that represents the builtins of the given stage.
  44295. */
  44296. getBuiltins( shaderStage ) {
  44297. const snippets = [];
  44298. const builtins = this.builtins[ shaderStage ];
  44299. if ( builtins !== undefined ) {
  44300. for ( const { name, property, type } of builtins.values() ) {
  44301. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  44302. }
  44303. }
  44304. return snippets.join( ',\n\t' );
  44305. }
  44306. /**
  44307. * This method should be used when a new scoped buffer is used in context of
  44308. * compute shaders. It adds the array to the internal data structure which is
  44309. * later used to generate the respective WGSL.
  44310. *
  44311. * @param {String} name - The array name.
  44312. * @param {String} scope - The scope.
  44313. * @param {String} bufferType - The buffer type.
  44314. * @param {String} bufferCount - The buffer count.
  44315. * @return {String} The array name.
  44316. */
  44317. getScopedArray( name, scope, bufferType, bufferCount ) {
  44318. if ( this.scopedArrays.has( name ) === false ) {
  44319. this.scopedArrays.set( name, {
  44320. name,
  44321. scope,
  44322. bufferType,
  44323. bufferCount
  44324. } );
  44325. }
  44326. return name;
  44327. }
  44328. /**
  44329. * Returns the scoped arrays of the given shader stage as a WGSL string.
  44330. *
  44331. * @param {String} shaderStage - The shader stage.
  44332. * @return {String|undefined} The WGSL snippet that defines the scoped arrays.
  44333. * Returns `undefined` when used in the vertex or fragment stage.
  44334. */
  44335. getScopedArrays( shaderStage ) {
  44336. if ( shaderStage !== 'compute' ) {
  44337. return;
  44338. }
  44339. const snippets = [];
  44340. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  44341. const type = this.getType( bufferType );
  44342. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  44343. }
  44344. return snippets.join( '\n' );
  44345. }
  44346. /**
  44347. * Returns the shader attributes of the given shader stage as a WGSL string.
  44348. *
  44349. * @param {String} shaderStage - The shader stage.
  44350. * @return {String} The WGSL snippet that defines the shader attributes.
  44351. */
  44352. getAttributes( shaderStage ) {
  44353. const snippets = [];
  44354. if ( shaderStage === 'compute' ) {
  44355. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  44356. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  44357. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  44358. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  44359. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  44360. this.enableDirective( 'subgroups', shaderStage );
  44361. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  44362. }
  44363. }
  44364. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  44365. const builtins = this.getBuiltins( 'attribute' );
  44366. if ( builtins ) snippets.push( builtins );
  44367. const attributes = this.getAttributesArray();
  44368. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  44369. const attribute = attributes[ index ];
  44370. const name = attribute.name;
  44371. const type = this.getType( attribute.type );
  44372. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  44373. }
  44374. }
  44375. return snippets.join( ',\n\t' );
  44376. }
  44377. /**
  44378. * Returns the members of the given struct type node as a WGSL string.
  44379. *
  44380. * @param {StructTypeNode} struct - The struct type node.
  44381. * @return {String} The WGSL snippet that defines the struct members.
  44382. */
  44383. getStructMembers( struct ) {
  44384. const snippets = [];
  44385. const members = struct.getMemberTypes();
  44386. for ( let i = 0; i < members.length; i ++ ) {
  44387. const member = members[ i ];
  44388. snippets.push( `\t@location( ${i} ) m${i} : ${ member }<f32>` );
  44389. }
  44390. const builtins = this.getBuiltins( 'output' );
  44391. if ( builtins ) snippets.push( '\t' + builtins );
  44392. return snippets.join( ',\n' );
  44393. }
  44394. /**
  44395. * Returns the structs of the given shader stage as a WGSL string.
  44396. *
  44397. * @param {String} shaderStage - The shader stage.
  44398. * @return {String} The WGSL snippet that defines the structs.
  44399. */
  44400. getStructs( shaderStage ) {
  44401. const snippets = [];
  44402. const structs = this.structs[ shaderStage ];
  44403. for ( let index = 0, length = structs.length; index < length; index ++ ) {
  44404. const struct = structs[ index ];
  44405. const name = struct.name;
  44406. let snippet = `\struct ${ name } {\n`;
  44407. snippet += this.getStructMembers( struct );
  44408. snippet += '\n}';
  44409. snippets.push( snippet );
  44410. snippets.push( `\nvar<private> output : ${ name };\n\n` );
  44411. }
  44412. return snippets.join( '\n\n' );
  44413. }
  44414. /**
  44415. * Returns a WGSL string representing a variable.
  44416. *
  44417. * @param {String} type - The variable's type.
  44418. * @param {String} name - The variable's name.
  44419. * @return {String} The WGSL snippet that defines a variable.
  44420. */
  44421. getVar( type, name ) {
  44422. return `var ${ name } : ${ this.getType( type ) }`;
  44423. }
  44424. /**
  44425. * Returns the variables of the given shader stage as a WGSL string.
  44426. *
  44427. * @param {String} shaderStage - The shader stage.
  44428. * @return {String} The WGSL snippet that defines the variables.
  44429. */
  44430. getVars( shaderStage ) {
  44431. const snippets = [];
  44432. const vars = this.vars[ shaderStage ];
  44433. if ( vars !== undefined ) {
  44434. for ( const variable of vars ) {
  44435. snippets.push( `\t${ this.getVar( variable.type, variable.name ) };` );
  44436. }
  44437. }
  44438. return `\n${ snippets.join( '\n' ) }\n`;
  44439. }
  44440. /**
  44441. * Returns the varyings of the given shader stage as a WGSL string.
  44442. *
  44443. * @param {String} shaderStage - The shader stage.
  44444. * @return {String} The WGSL snippet that defines the varyings.
  44445. */
  44446. getVaryings( shaderStage ) {
  44447. const snippets = [];
  44448. if ( shaderStage === 'vertex' ) {
  44449. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  44450. }
  44451. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  44452. const varyings = this.varyings;
  44453. const vars = this.vars[ shaderStage ];
  44454. for ( let index = 0; index < varyings.length; index ++ ) {
  44455. const varying = varyings[ index ];
  44456. if ( varying.needsInterpolation ) {
  44457. let attributesSnippet = `@location( ${index} )`;
  44458. if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  44459. attributesSnippet += ' @interpolate( flat )';
  44460. }
  44461. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  44462. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  44463. vars.push( varying );
  44464. }
  44465. }
  44466. }
  44467. const builtins = this.getBuiltins( shaderStage );
  44468. if ( builtins ) snippets.push( builtins );
  44469. const code = snippets.join( ',\n\t' );
  44470. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  44471. }
  44472. /**
  44473. * Returns the uniforms of the given shader stage as a WGSL string.
  44474. *
  44475. * @param {String} shaderStage - The shader stage.
  44476. * @return {String} The WGSL snippet that defines the uniforms.
  44477. */
  44478. getUniforms( shaderStage ) {
  44479. const uniforms = this.uniforms[ shaderStage ];
  44480. const bindingSnippets = [];
  44481. const bufferSnippets = [];
  44482. const structSnippets = [];
  44483. const uniformGroups = {};
  44484. for ( const uniform of uniforms ) {
  44485. const groupName = uniform.groupNode.name;
  44486. const uniformIndexes = this.bindingsIndexes[ groupName ];
  44487. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  44488. const texture = uniform.node.value;
  44489. if ( ( shaderStage === 'fragment' || shaderStage === 'compute' ) && this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  44490. if ( this.isSampleCompare( texture ) ) {
  44491. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  44492. } else {
  44493. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  44494. }
  44495. }
  44496. let textureType;
  44497. let multisampled = '';
  44498. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  44499. if ( primarySamples > 1 ) {
  44500. multisampled = '_multisampled';
  44501. }
  44502. if ( texture.isCubeTexture === true ) {
  44503. textureType = 'texture_cube<f32>';
  44504. } else if ( texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44505. textureType = 'texture_2d_array<f32>';
  44506. } else if ( texture.isDepthTexture === true ) {
  44507. textureType = `texture_depth${multisampled}_2d`;
  44508. } else if ( texture.isVideoTexture === true ) {
  44509. textureType = 'texture_external';
  44510. } else if ( texture.isData3DTexture === true ) {
  44511. textureType = 'texture_3d<f32>';
  44512. } else if ( uniform.node.isStorageTextureNode === true ) {
  44513. const format = getFormat( texture );
  44514. const access = this.getStorageAccess( uniform.node, shaderStage );
  44515. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  44516. } else {
  44517. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  44518. textureType = `texture${multisampled}_2d<${ componentPrefix }32>`;
  44519. }
  44520. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  44521. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  44522. const bufferNode = uniform.node;
  44523. const bufferType = this.getType( bufferNode.bufferType );
  44524. const bufferCount = bufferNode.bufferCount;
  44525. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  44526. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${bufferType}>` : `${bufferType}`;
  44527. const bufferSnippet = `\t${ uniform.name } : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >\n`;
  44528. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  44529. bufferSnippets.push( this._getWGSLStructBinding( 'NodeBuffer_' + bufferNode.id, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  44530. } else {
  44531. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  44532. const groupName = uniform.groupNode.name;
  44533. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  44534. index: uniformIndexes.binding ++,
  44535. id: uniformIndexes.group,
  44536. snippets: []
  44537. } );
  44538. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  44539. }
  44540. }
  44541. for ( const name in uniformGroups ) {
  44542. const group = uniformGroups[ name ];
  44543. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  44544. }
  44545. let code = bindingSnippets.join( '\n' );
  44546. code += bufferSnippets.join( '\n' );
  44547. code += structSnippets.join( '\n' );
  44548. return code;
  44549. }
  44550. /**
  44551. * Controls the code build of the shader stages.
  44552. */
  44553. buildCode() {
  44554. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  44555. this.sortBindingGroups();
  44556. for ( const shaderStage in shadersData ) {
  44557. const stageData = shadersData[ shaderStage ];
  44558. stageData.uniforms = this.getUniforms( shaderStage );
  44559. stageData.attributes = this.getAttributes( shaderStage );
  44560. stageData.varyings = this.getVaryings( shaderStage );
  44561. stageData.structs = this.getStructs( shaderStage );
  44562. stageData.vars = this.getVars( shaderStage );
  44563. stageData.codes = this.getCodes( shaderStage );
  44564. stageData.directives = this.getDirectives( shaderStage );
  44565. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  44566. //
  44567. let flow = '// code\n\n';
  44568. flow += this.flowCode[ shaderStage ];
  44569. const flowNodes = this.flowNodes[ shaderStage ];
  44570. const mainNode = flowNodes[ flowNodes.length - 1 ];
  44571. const outputNode = mainNode.outputNode;
  44572. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  44573. for ( const node of flowNodes ) {
  44574. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  44575. const slotName = node.name;
  44576. if ( slotName ) {
  44577. if ( flow.length > 0 ) flow += '\n';
  44578. flow += `\t// flow -> ${ slotName }\n`;
  44579. }
  44580. flow += `${ flowSlotData.code }\n\t`;
  44581. if ( node === mainNode && shaderStage !== 'compute' ) {
  44582. flow += '// result\n\n\t';
  44583. if ( shaderStage === 'vertex' ) {
  44584. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  44585. } else if ( shaderStage === 'fragment' ) {
  44586. if ( isOutputStruct ) {
  44587. stageData.returnType = outputNode.nodeType;
  44588. flow += `return ${ flowSlotData.result };`;
  44589. } else {
  44590. let structSnippet = '\t@location(0) color: vec4<f32>';
  44591. const builtins = this.getBuiltins( 'output' );
  44592. if ( builtins ) structSnippet += ',\n\t' + builtins;
  44593. stageData.returnType = 'OutputStruct';
  44594. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  44595. stageData.structs += '\nvar<private> output : OutputStruct;\n\n';
  44596. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  44597. }
  44598. }
  44599. }
  44600. }
  44601. stageData.flow = flow;
  44602. }
  44603. if ( this.material !== null ) {
  44604. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  44605. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  44606. } else {
  44607. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  44608. }
  44609. }
  44610. /**
  44611. * Returns the native shader method name for a given generic name.
  44612. *
  44613. * @param {String} method - The method name to resolve.
  44614. * @param {String} [output=null] - An optional output.
  44615. * @return {String} The resolved WGSL method name.
  44616. */
  44617. getMethod( method, output = null ) {
  44618. let wgslMethod;
  44619. if ( output !== null ) {
  44620. wgslMethod = this._getWGSLMethod( method + '_' + output );
  44621. }
  44622. if ( wgslMethod === undefined ) {
  44623. wgslMethod = this._getWGSLMethod( method );
  44624. }
  44625. return wgslMethod || method;
  44626. }
  44627. /**
  44628. * Returns the WGSL type of the given node data type.
  44629. *
  44630. * @param {String} type - The node data type.
  44631. * @return {String} The WGSL type.
  44632. */
  44633. getType( type ) {
  44634. return wgslTypeLib[ type ] || type;
  44635. }
  44636. /**
  44637. * Whether the requested feature is available or not.
  44638. *
  44639. * @param {String} name - The requested feature.
  44640. * @return {Boolean} Whether the requested feature is supported or not.
  44641. */
  44642. isAvailable( name ) {
  44643. let result = supports[ name ];
  44644. if ( result === undefined ) {
  44645. if ( name === 'float32Filterable' ) {
  44646. result = this.renderer.hasFeature( 'float32-filterable' );
  44647. } else if ( name === 'clipDistance' ) {
  44648. result = this.renderer.hasFeature( 'clip-distances' );
  44649. }
  44650. supports[ name ] = result;
  44651. }
  44652. return result;
  44653. }
  44654. /**
  44655. * Returns the native shader method name for a given generic name.
  44656. *
  44657. * @private
  44658. * @param {String} method - The method name to resolve.
  44659. * @return {String} The resolved WGSL method name.
  44660. */
  44661. _getWGSLMethod( method ) {
  44662. if ( wgslPolyfill[ method ] !== undefined ) {
  44663. this._include( method );
  44664. }
  44665. return wgslMethods[ method ];
  44666. }
  44667. /**
  44668. * Includes the given method name into the current
  44669. * function node.
  44670. *
  44671. * @private
  44672. * @param {String} name - The method name to include.
  44673. * @return {CodeNode} The respective code node.
  44674. */
  44675. _include( name ) {
  44676. const codeNode = wgslPolyfill[ name ];
  44677. codeNode.build( this );
  44678. if ( this.currentFunctionNode !== null ) {
  44679. this.currentFunctionNode.includes.push( codeNode );
  44680. }
  44681. return codeNode;
  44682. }
  44683. /**
  44684. * Returns a WGSL vertex shader based on the given shader data.
  44685. *
  44686. * @private
  44687. * @param {Object} shaderData - The shader data.
  44688. * @return {String} The vertex shader.
  44689. */
  44690. _getWGSLVertexCode( shaderData ) {
  44691. return `${ this.getSignature() }
  44692. // directives
  44693. ${shaderData.directives}
  44694. // uniforms
  44695. ${shaderData.uniforms}
  44696. // varyings
  44697. ${shaderData.varyings}
  44698. var<private> varyings : VaryingsStruct;
  44699. // codes
  44700. ${shaderData.codes}
  44701. @vertex
  44702. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  44703. // vars
  44704. ${shaderData.vars}
  44705. // flow
  44706. ${shaderData.flow}
  44707. return varyings;
  44708. }
  44709. `;
  44710. }
  44711. /**
  44712. * Returns a WGSL fragment shader based on the given shader data.
  44713. *
  44714. * @private
  44715. * @param {Object} shaderData - The shader data.
  44716. * @return {String} The vertex shader.
  44717. */
  44718. _getWGSLFragmentCode( shaderData ) {
  44719. return `${ this.getSignature() }
  44720. // global
  44721. ${ diagnostics }
  44722. // uniforms
  44723. ${shaderData.uniforms}
  44724. // structs
  44725. ${shaderData.structs}
  44726. // codes
  44727. ${shaderData.codes}
  44728. @fragment
  44729. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  44730. // vars
  44731. ${shaderData.vars}
  44732. // flow
  44733. ${shaderData.flow}
  44734. }
  44735. `;
  44736. }
  44737. /**
  44738. * Returns a WGSL compute shader based on the given shader data.
  44739. *
  44740. * @private
  44741. * @param {Object} shaderData - The shader data.
  44742. * @param {String} workgroupSize - The workgroup size.
  44743. * @return {String} The vertex shader.
  44744. */
  44745. _getWGSLComputeCode( shaderData, workgroupSize ) {
  44746. return `${ this.getSignature() }
  44747. // directives
  44748. ${shaderData.directives}
  44749. // system
  44750. var<private> instanceIndex : u32;
  44751. // locals
  44752. ${shaderData.scopedArrays}
  44753. // uniforms
  44754. ${shaderData.uniforms}
  44755. // codes
  44756. ${shaderData.codes}
  44757. @compute @workgroup_size( ${workgroupSize} )
  44758. fn main( ${shaderData.attributes} ) {
  44759. // system
  44760. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  44761. // vars
  44762. ${shaderData.vars}
  44763. // flow
  44764. ${shaderData.flow}
  44765. }
  44766. `;
  44767. }
  44768. /**
  44769. * Returns a WGSL struct based on the given name and variables.
  44770. *
  44771. * @private
  44772. * @param {String} name - The struct name.
  44773. * @param {String} vars - The struct variables.
  44774. * @return {String} The WGSL snippet representing a struct.
  44775. */
  44776. _getWGSLStruct( name, vars ) {
  44777. return `
  44778. struct ${name} {
  44779. ${vars}
  44780. };`;
  44781. }
  44782. /**
  44783. * Returns a WGSL struct binding.
  44784. *
  44785. * @private
  44786. * @param {String} name - The struct name.
  44787. * @param {String} vars - The struct variables.
  44788. * @param {String} access - The access.
  44789. * @param {Number} [binding=0] - The binding index.
  44790. * @param {Number} [group=0] - The group index.
  44791. * @return {String} The WGSL snippet representing a struct binding.
  44792. */
  44793. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  44794. const structName = name + 'Struct';
  44795. const structSnippet = this._getWGSLStruct( structName, vars );
  44796. return `${structSnippet}
  44797. @binding( ${binding} ) @group( ${group} )
  44798. var<${access}> ${name} : ${structName};`;
  44799. }
  44800. }
  44801. /**
  44802. * A WebGPU backend utility module with common helpers.
  44803. *
  44804. * @private
  44805. */
  44806. class WebGPUUtils {
  44807. /**
  44808. * Constructs a new utility object.
  44809. *
  44810. * @param {WebGPUBackend} backend - The WebGPU backend.
  44811. */
  44812. constructor( backend ) {
  44813. /**
  44814. * A reference to the WebGPU backend.
  44815. *
  44816. * @type {WebGPUBackend}
  44817. */
  44818. this.backend = backend;
  44819. }
  44820. /**
  44821. * Returns the depth/stencil GPU format for the given render context.
  44822. *
  44823. * @param {RenderContext} renderContext - The render context.
  44824. * @return {String} The depth/stencil GPU texture format.
  44825. */
  44826. getCurrentDepthStencilFormat( renderContext ) {
  44827. let format;
  44828. if ( renderContext.depthTexture !== null ) {
  44829. format = this.getTextureFormatGPU( renderContext.depthTexture );
  44830. } else if ( renderContext.depth && renderContext.stencil ) {
  44831. format = GPUTextureFormat.Depth24PlusStencil8;
  44832. } else if ( renderContext.depth ) {
  44833. format = GPUTextureFormat.Depth24Plus;
  44834. }
  44835. return format;
  44836. }
  44837. /**
  44838. * Returns the GPU format for the given texture.
  44839. *
  44840. * @param {Texture} texture - The texture.
  44841. * @return {String} The GPU texture format.
  44842. */
  44843. getTextureFormatGPU( texture ) {
  44844. return this.backend.get( texture ).format;
  44845. }
  44846. /**
  44847. * Returns an object that defines the multi-sampling state of the given texture.
  44848. *
  44849. * @param {Texture} texture - The texture.
  44850. * @return {Object} The multi-sampling state.
  44851. */
  44852. getTextureSampleData( texture ) {
  44853. let samples;
  44854. if ( texture.isFramebufferTexture ) {
  44855. samples = 1;
  44856. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  44857. const renderer = this.backend.renderer;
  44858. const renderTarget = renderer.getRenderTarget();
  44859. samples = renderTarget ? renderTarget.samples : renderer.samples;
  44860. } else if ( texture.renderTarget ) {
  44861. samples = texture.renderTarget.samples;
  44862. }
  44863. samples = samples || 1;
  44864. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  44865. const primarySamples = isMSAA ? 1 : samples;
  44866. return { samples, primarySamples, isMSAA };
  44867. }
  44868. /**
  44869. * Returns the default color attachment's GPU format of the current render context.
  44870. *
  44871. * @param {RenderContext} renderContext - The render context.
  44872. * @return {String} The GPU texture format of the default color attachment.
  44873. */
  44874. getCurrentColorFormat( renderContext ) {
  44875. let format;
  44876. if ( renderContext.textures !== null ) {
  44877. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  44878. } else {
  44879. format = this.getPreferredCanvasFormat(); // default context format
  44880. }
  44881. return format;
  44882. }
  44883. /**
  44884. * Returns the output color space of the current render context.
  44885. *
  44886. * @param {RenderContext} renderContext - The render context.
  44887. * @return {String} The output color space.
  44888. */
  44889. getCurrentColorSpace( renderContext ) {
  44890. if ( renderContext.textures !== null ) {
  44891. return renderContext.textures[ 0 ].colorSpace;
  44892. }
  44893. return this.backend.renderer.outputColorSpace;
  44894. }
  44895. /**
  44896. * Returns GPU primitive topology for the given object and material.
  44897. *
  44898. * @param {Object3D} object - The 3D object.
  44899. * @param {Material} material - The material.
  44900. * @return {String} The GPU primitive topology.
  44901. */
  44902. getPrimitiveTopology( object, material ) {
  44903. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  44904. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  44905. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  44906. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  44907. }
  44908. /**
  44909. * Returns a modified sample count from the given sample count value.
  44910. *
  44911. * That is required since WebGPU does not support arbitrary sample counts.
  44912. *
  44913. * @param {Number} sampleCount - The input sample count.
  44914. * @return {Number} The (potentially updated) output sample count.
  44915. */
  44916. getSampleCount( sampleCount ) {
  44917. let count = 1;
  44918. if ( sampleCount > 1 ) {
  44919. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  44920. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  44921. if ( count === 2 ) {
  44922. count = 4;
  44923. }
  44924. }
  44925. return count;
  44926. }
  44927. /**
  44928. * Returns the sample count of the given render context.
  44929. *
  44930. * @param {RenderContext} renderContext - The render context.
  44931. * @return {Number} The sample count.
  44932. */
  44933. getSampleCountRenderContext( renderContext ) {
  44934. if ( renderContext.textures !== null ) {
  44935. return this.getSampleCount( renderContext.sampleCount );
  44936. }
  44937. return this.getSampleCount( this.backend.renderer.samples );
  44938. }
  44939. /**
  44940. * Returns the preferred canvas format.
  44941. *
  44942. * There is a separate method for this so it's possible to
  44943. * honor edge cases for specific devices.
  44944. *
  44945. * @return {String} The GPU texture format of the canvas.
  44946. */
  44947. getPreferredCanvasFormat() {
  44948. const outputType = this.backend.parameters.outputType;
  44949. if ( outputType === undefined ) {
  44950. return navigator.gpu.getPreferredCanvasFormat();
  44951. } else if ( outputType === UnsignedByteType ) {
  44952. return GPUTextureFormat.BGRA8Unorm;
  44953. } else if ( outputType === HalfFloatType ) {
  44954. return GPUTextureFormat.RGBA16Float;
  44955. } else {
  44956. throw new Error( 'Unsupported outputType' );
  44957. }
  44958. }
  44959. }
  44960. const typedArraysToVertexFormatPrefix = new Map( [
  44961. [ Int8Array, [ 'sint8', 'snorm8' ]],
  44962. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  44963. [ Int16Array, [ 'sint16', 'snorm16' ]],
  44964. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  44965. [ Int32Array, [ 'sint32', 'snorm32' ]],
  44966. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  44967. [ Float32Array, [ 'float32', ]],
  44968. ] );
  44969. const typedAttributeToVertexFormatPrefix = new Map( [
  44970. [ Float16BufferAttribute, [ 'float16', ]],
  44971. ] );
  44972. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  44973. [ Int32Array, 'sint32' ],
  44974. [ Int16Array, 'sint32' ], // patch for INT16
  44975. [ Uint32Array, 'uint32' ],
  44976. [ Uint16Array, 'uint32' ], // patch for UINT16
  44977. [ Float32Array, 'float32' ]
  44978. ] );
  44979. /**
  44980. * A WebGPU backend utility module for managing shader attributes.
  44981. *
  44982. * @private
  44983. */
  44984. class WebGPUAttributeUtils {
  44985. /**
  44986. * Constructs a new utility object.
  44987. *
  44988. * @param {WebGPUBackend} backend - The WebGPU backend.
  44989. */
  44990. constructor( backend ) {
  44991. /**
  44992. * A reference to the WebGPU backend.
  44993. *
  44994. * @type {WebGPUBackend}
  44995. */
  44996. this.backend = backend;
  44997. }
  44998. /**
  44999. * Creates the GPU buffer for the given buffer attribute.
  45000. *
  45001. * @param {BufferAttribute} attribute - The buffer attribute.
  45002. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  45003. */
  45004. createAttribute( attribute, usage ) {
  45005. const bufferAttribute = this._getBufferAttribute( attribute );
  45006. const backend = this.backend;
  45007. const bufferData = backend.get( bufferAttribute );
  45008. let buffer = bufferData.buffer;
  45009. if ( buffer === undefined ) {
  45010. const device = backend.device;
  45011. let array = bufferAttribute.array;
  45012. // patch for INT16 and UINT16
  45013. if ( attribute.normalized === false ) {
  45014. if ( array.constructor === Int16Array ) {
  45015. array = new Int32Array( array );
  45016. } else if ( array.constructor === Uint16Array ) {
  45017. array = new Uint32Array( array );
  45018. if ( usage & GPUBufferUsage.INDEX ) {
  45019. for ( let i = 0; i < array.length; i ++ ) {
  45020. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  45021. }
  45022. }
  45023. }
  45024. }
  45025. bufferAttribute.array = array;
  45026. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  45027. array = new array.constructor( bufferAttribute.count * 4 );
  45028. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  45029. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  45030. }
  45031. // Update BufferAttribute
  45032. bufferAttribute.itemSize = 4;
  45033. bufferAttribute.array = array;
  45034. }
  45035. const size = array.byteLength + ( ( 4 - ( array.byteLength % 4 ) ) % 4 ); // ensure 4 byte alignment, see #20441
  45036. buffer = device.createBuffer( {
  45037. label: bufferAttribute.name,
  45038. size: size,
  45039. usage: usage,
  45040. mappedAtCreation: true
  45041. } );
  45042. new array.constructor( buffer.getMappedRange() ).set( array );
  45043. buffer.unmap();
  45044. bufferData.buffer = buffer;
  45045. }
  45046. }
  45047. /**
  45048. * Updates the GPU buffer of the given buffer attribute.
  45049. *
  45050. * @param {BufferAttribute} attribute - The buffer attribute.
  45051. */
  45052. updateAttribute( attribute ) {
  45053. const bufferAttribute = this._getBufferAttribute( attribute );
  45054. const backend = this.backend;
  45055. const device = backend.device;
  45056. const buffer = backend.get( bufferAttribute ).buffer;
  45057. const array = bufferAttribute.array;
  45058. const isTypedArray = this._isTypedArray( array );
  45059. const updateRanges = bufferAttribute.updateRanges;
  45060. if ( updateRanges.length === 0 ) {
  45061. // Not using update ranges
  45062. device.queue.writeBuffer(
  45063. buffer,
  45064. 0,
  45065. array,
  45066. 0
  45067. );
  45068. } else {
  45069. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  45070. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  45071. const range = updateRanges[ i ];
  45072. const dataOffset = range.start * byteOffsetFactor;
  45073. const size = range.count * byteOffsetFactor;
  45074. device.queue.writeBuffer(
  45075. buffer,
  45076. 0,
  45077. array,
  45078. dataOffset,
  45079. size
  45080. );
  45081. }
  45082. bufferAttribute.clearUpdateRanges();
  45083. }
  45084. }
  45085. /**
  45086. * This method creates the vertex buffer layout data which are
  45087. * require when creating a render pipeline for the given render object.
  45088. *
  45089. * @param {RenderObject} renderObject - The render object.
  45090. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  45091. */
  45092. createShaderVertexBuffers( renderObject ) {
  45093. const attributes = renderObject.getAttributes();
  45094. const vertexBuffers = new Map();
  45095. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  45096. const geometryAttribute = attributes[ slot ];
  45097. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  45098. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  45099. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  45100. if ( vertexBufferLayout === undefined ) {
  45101. let arrayStride, stepMode;
  45102. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  45103. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  45104. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45105. } else {
  45106. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  45107. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  45108. }
  45109. // patch for INT16 and UINT16
  45110. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  45111. arrayStride = 4;
  45112. }
  45113. vertexBufferLayout = {
  45114. arrayStride,
  45115. attributes: [],
  45116. stepMode
  45117. };
  45118. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  45119. }
  45120. const format = this._getVertexFormat( geometryAttribute );
  45121. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  45122. vertexBufferLayout.attributes.push( {
  45123. shaderLocation: slot,
  45124. offset,
  45125. format
  45126. } );
  45127. }
  45128. return Array.from( vertexBuffers.values() );
  45129. }
  45130. /**
  45131. * Destroys the GPU buffer of the given buffer attribute.
  45132. *
  45133. * @param {BufferAttribute} attribute - The buffer attribute.
  45134. */
  45135. destroyAttribute( attribute ) {
  45136. const backend = this.backend;
  45137. const data = backend.get( this._getBufferAttribute( attribute ) );
  45138. data.buffer.destroy();
  45139. backend.delete( attribute );
  45140. }
  45141. /**
  45142. * This method performs a readback operation by moving buffer data from
  45143. * a storage buffer attribute from the GPU to the CPU.
  45144. *
  45145. * @async
  45146. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45147. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45148. */
  45149. async getArrayBufferAsync( attribute ) {
  45150. const backend = this.backend;
  45151. const device = backend.device;
  45152. const data = backend.get( this._getBufferAttribute( attribute ) );
  45153. const bufferGPU = data.buffer;
  45154. const size = bufferGPU.size;
  45155. const readBufferGPU = device.createBuffer( {
  45156. label: `${ attribute.name }_readback`,
  45157. size,
  45158. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  45159. } );
  45160. const cmdEncoder = device.createCommandEncoder( {
  45161. label: `readback_encoder_${ attribute.name }`
  45162. } );
  45163. cmdEncoder.copyBufferToBuffer(
  45164. bufferGPU,
  45165. 0,
  45166. readBufferGPU,
  45167. 0,
  45168. size
  45169. );
  45170. const gpuCommands = cmdEncoder.finish();
  45171. device.queue.submit( [ gpuCommands ] );
  45172. await readBufferGPU.mapAsync( GPUMapMode.READ );
  45173. const arrayBuffer = readBufferGPU.getMappedRange();
  45174. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  45175. readBufferGPU.unmap();
  45176. return dstBuffer.buffer;
  45177. }
  45178. /**
  45179. * Returns the vertex format of the given buffer attribute.
  45180. *
  45181. * @private
  45182. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  45183. * @return {String} The vertex format (e.g. 'float32x3').
  45184. */
  45185. _getVertexFormat( geometryAttribute ) {
  45186. const { itemSize, normalized } = geometryAttribute;
  45187. const ArrayType = geometryAttribute.array.constructor;
  45188. const AttributeType = geometryAttribute.constructor;
  45189. let format;
  45190. if ( itemSize === 1 ) {
  45191. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  45192. } else {
  45193. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  45194. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  45195. if ( prefix ) {
  45196. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  45197. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  45198. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  45199. if ( paddedItemSize % 1 ) {
  45200. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  45201. }
  45202. format = `${prefix}x${paddedItemSize}`;
  45203. }
  45204. }
  45205. if ( ! format ) {
  45206. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  45207. }
  45208. return format;
  45209. }
  45210. /**
  45211. * Returns `true` if the given array is a typed array.
  45212. *
  45213. * @private
  45214. * @param {Any} array - The array.
  45215. * @return {Boolean} Whether the given array is a typed array or not.
  45216. */
  45217. _isTypedArray( array ) {
  45218. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  45219. }
  45220. /**
  45221. * Utility method for handling interleaved buffer attributes correctly.
  45222. * To process them, their `InterleavedBuffer` is returned.
  45223. *
  45224. * @private
  45225. * @param {BufferAttribute} attribute - The attribute.
  45226. * @return {BufferAttribute|InterleavedBuffer}
  45227. */
  45228. _getBufferAttribute( attribute ) {
  45229. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  45230. return attribute;
  45231. }
  45232. }
  45233. /**
  45234. * A WebGPU backend utility module for managing bindings.
  45235. *
  45236. * When reading the documentation it's helpful to keep in mind that
  45237. * all class definitions starting with 'GPU*' are modules from the
  45238. * WebGPU API. So for example `BindGroup` is a class from the engine
  45239. * whereas `GPUBindGroup` is a class from WebGPU.
  45240. *
  45241. * @private
  45242. */
  45243. class WebGPUBindingUtils {
  45244. /**
  45245. * Constructs a new utility object.
  45246. *
  45247. * @param {WebGPUBackend} backend - The WebGPU backend.
  45248. */
  45249. constructor( backend ) {
  45250. /**
  45251. * A reference to the WebGPU backend.
  45252. *
  45253. * @type {WebGPUBackend}
  45254. */
  45255. this.backend = backend;
  45256. /**
  45257. * A cache for managing bind group layouts.
  45258. *
  45259. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  45260. */
  45261. this.bindGroupLayoutCache = new WeakMap();
  45262. }
  45263. /**
  45264. * Creates a GPU bind group layout for the given bind group.
  45265. *
  45266. * @param {BindGroup} bindGroup - The bind group.
  45267. * @return {GPUBindGroupLayout} The GPU bind group layout.
  45268. */
  45269. createBindingsLayout( bindGroup ) {
  45270. const backend = this.backend;
  45271. const device = backend.device;
  45272. const entries = [];
  45273. let index = 0;
  45274. for ( const binding of bindGroup.bindings ) {
  45275. const bindingGPU = {
  45276. binding: index ++,
  45277. visibility: binding.visibility
  45278. };
  45279. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  45280. const buffer = {}; // GPUBufferBindingLayout
  45281. if ( binding.isStorageBuffer ) {
  45282. if ( binding.visibility & 4 ) {
  45283. // compute
  45284. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  45285. buffer.type = GPUBufferBindingType.Storage;
  45286. } else {
  45287. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45288. }
  45289. } else {
  45290. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  45291. }
  45292. }
  45293. bindingGPU.buffer = buffer;
  45294. } else if ( binding.isSampler ) {
  45295. const sampler = {}; // GPUSamplerBindingLayout
  45296. if ( binding.texture.isDepthTexture ) {
  45297. if ( binding.texture.compareFunction !== null ) {
  45298. sampler.type = 'comparison';
  45299. }
  45300. }
  45301. bindingGPU.sampler = sampler;
  45302. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  45303. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  45304. } else if ( binding.isSampledTexture && binding.store ) {
  45305. const storageTexture = {}; // GPUStorageTextureBindingLayout
  45306. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  45307. const access = binding.access;
  45308. if ( access === NodeAccess.READ_WRITE ) {
  45309. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  45310. } else if ( access === NodeAccess.WRITE_ONLY ) {
  45311. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  45312. } else {
  45313. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  45314. }
  45315. bindingGPU.storageTexture = storageTexture;
  45316. } else if ( binding.isSampledTexture ) {
  45317. const texture = {}; // GPUTextureBindingLayout
  45318. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  45319. if ( primarySamples > 1 ) {
  45320. texture.multisampled = true;
  45321. if ( ! binding.texture.isDepthTexture ) {
  45322. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  45323. }
  45324. }
  45325. if ( binding.texture.isDepthTexture ) {
  45326. texture.sampleType = GPUTextureSampleType.Depth;
  45327. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  45328. const type = binding.texture.type;
  45329. if ( type === IntType ) {
  45330. texture.sampleType = GPUTextureSampleType.SInt;
  45331. } else if ( type === UnsignedIntType ) {
  45332. texture.sampleType = GPUTextureSampleType.UInt;
  45333. } else if ( type === FloatType ) {
  45334. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  45335. texture.sampleType = GPUTextureSampleType.Float;
  45336. } else {
  45337. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  45338. }
  45339. }
  45340. }
  45341. if ( binding.isSampledCubeTexture ) {
  45342. texture.viewDimension = GPUTextureViewDimension.Cube;
  45343. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  45344. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  45345. } else if ( binding.isSampledTexture3D ) {
  45346. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  45347. }
  45348. bindingGPU.texture = texture;
  45349. } else {
  45350. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  45351. }
  45352. entries.push( bindingGPU );
  45353. }
  45354. return device.createBindGroupLayout( { entries } );
  45355. }
  45356. /**
  45357. * Creates bindings from the given bind group definition.
  45358. *
  45359. * @param {BindGroup} bindGroup - The bind group.
  45360. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45361. * @param {Number} cacheIndex - The cache index.
  45362. * @param {Number} version - The version.
  45363. */
  45364. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  45365. const { backend, bindGroupLayoutCache } = this;
  45366. const bindingsData = backend.get( bindGroup );
  45367. // setup (static) binding layout and (dynamic) binding group
  45368. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  45369. if ( bindLayoutGPU === undefined ) {
  45370. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  45371. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  45372. }
  45373. let bindGroupGPU;
  45374. if ( cacheIndex > 0 ) {
  45375. if ( bindingsData.groups === undefined ) {
  45376. bindingsData.groups = [];
  45377. bindingsData.versions = [];
  45378. }
  45379. if ( bindingsData.versions[ cacheIndex ] === version ) {
  45380. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  45381. }
  45382. }
  45383. if ( bindGroupGPU === undefined ) {
  45384. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  45385. if ( cacheIndex > 0 ) {
  45386. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  45387. bindingsData.versions[ cacheIndex ] = version;
  45388. }
  45389. }
  45390. bindingsData.group = bindGroupGPU;
  45391. bindingsData.layout = bindLayoutGPU;
  45392. }
  45393. /**
  45394. * Updates a buffer binding.
  45395. *
  45396. * @param {Buffer} binding - The buffer binding to update.
  45397. */
  45398. updateBinding( binding ) {
  45399. const backend = this.backend;
  45400. const device = backend.device;
  45401. const buffer = binding.buffer;
  45402. const bufferGPU = backend.get( binding ).buffer;
  45403. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  45404. }
  45405. /**
  45406. * Creates a GPU bind group for the camera index.
  45407. *
  45408. * @param {Uint32Array} data - The index data.
  45409. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  45410. * @return {GPUBindGroup} The GPU bind group.
  45411. */
  45412. createBindGroupIndex( data, layout ) {
  45413. const backend = this.backend;
  45414. const device = backend.device;
  45415. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  45416. const index = data[ 0 ];
  45417. const buffer = device.createBuffer( {
  45418. label: 'bindingCameraIndex_' + index,
  45419. size: 16, // uint(4) * 4
  45420. usage: usage
  45421. } );
  45422. device.queue.writeBuffer( buffer, 0, data, 0 );
  45423. const entries = [ { binding: 0, resource: { buffer } } ];
  45424. return device.createBindGroup( {
  45425. label: 'bindGroupCameraIndex_' + index,
  45426. layout,
  45427. entries
  45428. } );
  45429. }
  45430. /**
  45431. * Creates a GPU bind group for the given bind group and GPU layout.
  45432. *
  45433. * @param {BindGroup} bindGroup - The bind group.
  45434. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  45435. * @return {GPUBindGroup} The GPU bind group.
  45436. */
  45437. createBindGroup( bindGroup, layoutGPU ) {
  45438. const backend = this.backend;
  45439. const device = backend.device;
  45440. let bindingPoint = 0;
  45441. const entriesGPU = [];
  45442. for ( const binding of bindGroup.bindings ) {
  45443. if ( binding.isUniformBuffer ) {
  45444. const bindingData = backend.get( binding );
  45445. if ( bindingData.buffer === undefined ) {
  45446. const byteLength = binding.byteLength;
  45447. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  45448. const bufferGPU = device.createBuffer( {
  45449. label: 'bindingBuffer_' + binding.name,
  45450. size: byteLength,
  45451. usage: usage
  45452. } );
  45453. bindingData.buffer = bufferGPU;
  45454. }
  45455. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  45456. } else if ( binding.isStorageBuffer ) {
  45457. const bindingData = backend.get( binding );
  45458. if ( bindingData.buffer === undefined ) {
  45459. const attribute = binding.attribute;
  45460. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  45461. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  45462. bindingData.buffer = backend.get( attribute ).buffer;
  45463. }
  45464. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  45465. } else if ( binding.isSampler ) {
  45466. const textureGPU = backend.get( binding.texture );
  45467. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  45468. } else if ( binding.isSampledTexture ) {
  45469. const textureData = backend.get( binding.texture );
  45470. let resourceGPU;
  45471. if ( textureData.externalTexture !== undefined ) {
  45472. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  45473. } else {
  45474. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  45475. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  45476. resourceGPU = textureData[ propertyName ];
  45477. if ( resourceGPU === undefined ) {
  45478. const aspectGPU = GPUTextureAspect.All;
  45479. let dimensionViewGPU;
  45480. if ( binding.isSampledCubeTexture ) {
  45481. dimensionViewGPU = GPUTextureViewDimension.Cube;
  45482. } else if ( binding.isSampledTexture3D ) {
  45483. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  45484. } else if ( binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  45485. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  45486. } else {
  45487. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  45488. }
  45489. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  45490. }
  45491. }
  45492. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  45493. }
  45494. bindingPoint ++;
  45495. }
  45496. return device.createBindGroup( {
  45497. label: 'bindGroup_' + bindGroup.name,
  45498. layout: layoutGPU,
  45499. entries: entriesGPU
  45500. } );
  45501. }
  45502. }
  45503. /**
  45504. * A WebGPU backend utility module for managing pipelines.
  45505. *
  45506. * @private
  45507. */
  45508. class WebGPUPipelineUtils {
  45509. /**
  45510. * Constructs a new utility object.
  45511. *
  45512. * @param {WebGPUBackend} backend - The WebGPU backend.
  45513. */
  45514. constructor( backend ) {
  45515. /**
  45516. * A reference to the WebGPU backend.
  45517. *
  45518. * @type {WebGPUBackend}
  45519. */
  45520. this.backend = backend;
  45521. }
  45522. /**
  45523. * Returns the sample count derived from the given render context.
  45524. *
  45525. * @private
  45526. * @param {RenderContext} renderContext - The render context.
  45527. * @return {Number} The sample count.
  45528. */
  45529. _getSampleCount( renderContext ) {
  45530. return this.backend.utils.getSampleCountRenderContext( renderContext );
  45531. }
  45532. /**
  45533. * Creates a render pipeline for the given render object.
  45534. *
  45535. * @param {RenderObject} renderObject - The render object.
  45536. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45537. */
  45538. createRenderPipeline( renderObject, promises ) {
  45539. const { object, material, geometry, pipeline } = renderObject;
  45540. const { vertexProgram, fragmentProgram } = pipeline;
  45541. const backend = this.backend;
  45542. const device = backend.device;
  45543. const utils = backend.utils;
  45544. const pipelineData = backend.get( pipeline );
  45545. // bind group layouts
  45546. const bindGroupLayouts = [];
  45547. for ( const bindGroup of renderObject.getBindings() ) {
  45548. const bindingsData = backend.get( bindGroup );
  45549. bindGroupLayouts.push( bindingsData.layout );
  45550. }
  45551. // vertex buffers
  45552. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  45553. // blending
  45554. let blending;
  45555. if ( material.transparent === true && material.blending !== NoBlending ) {
  45556. blending = this._getBlending( material );
  45557. }
  45558. // stencil
  45559. let stencilFront = {};
  45560. if ( material.stencilWrite === true ) {
  45561. stencilFront = {
  45562. compare: this._getStencilCompare( material ),
  45563. failOp: this._getStencilOperation( material.stencilFail ),
  45564. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  45565. passOp: this._getStencilOperation( material.stencilZPass )
  45566. };
  45567. }
  45568. const colorWriteMask = this._getColorWriteMask( material );
  45569. const targets = [];
  45570. if ( renderObject.context.textures !== null ) {
  45571. const textures = renderObject.context.textures;
  45572. for ( let i = 0; i < textures.length; i ++ ) {
  45573. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  45574. targets.push( {
  45575. format: colorFormat,
  45576. blend: blending,
  45577. writeMask: colorWriteMask
  45578. } );
  45579. }
  45580. } else {
  45581. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  45582. targets.push( {
  45583. format: colorFormat,
  45584. blend: blending,
  45585. writeMask: colorWriteMask
  45586. } );
  45587. }
  45588. const vertexModule = backend.get( vertexProgram ).module;
  45589. const fragmentModule = backend.get( fragmentProgram ).module;
  45590. const primitiveState = this._getPrimitiveState( object, geometry, material );
  45591. const depthCompare = this._getDepthCompare( material );
  45592. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  45593. const sampleCount = this._getSampleCount( renderObject.context );
  45594. const pipelineDescriptor = {
  45595. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  45596. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  45597. fragment: Object.assign( {}, fragmentModule, { targets } ),
  45598. primitive: primitiveState,
  45599. multisample: {
  45600. count: sampleCount,
  45601. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  45602. },
  45603. layout: device.createPipelineLayout( {
  45604. bindGroupLayouts
  45605. } )
  45606. };
  45607. const depthStencil = {};
  45608. const renderDepth = renderObject.context.depth;
  45609. const renderStencil = renderObject.context.stencil;
  45610. if ( renderDepth === true || renderStencil === true ) {
  45611. if ( renderDepth === true ) {
  45612. depthStencil.format = depthStencilFormat;
  45613. depthStencil.depthWriteEnabled = material.depthWrite;
  45614. depthStencil.depthCompare = depthCompare;
  45615. }
  45616. if ( renderStencil === true ) {
  45617. depthStencil.stencilFront = stencilFront;
  45618. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  45619. depthStencil.stencilReadMask = material.stencilFuncMask;
  45620. depthStencil.stencilWriteMask = material.stencilWriteMask;
  45621. }
  45622. pipelineDescriptor.depthStencil = depthStencil;
  45623. }
  45624. if ( promises === null ) {
  45625. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  45626. } else {
  45627. const p = new Promise( ( resolve /*, reject*/ ) => {
  45628. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  45629. pipelineData.pipeline = pipeline;
  45630. resolve();
  45631. } );
  45632. } );
  45633. promises.push( p );
  45634. }
  45635. }
  45636. /**
  45637. * Creates GPU render bundle encoder for the given render context.
  45638. *
  45639. * @param {RenderContext} renderContext - The render context.
  45640. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  45641. */
  45642. createBundleEncoder( renderContext ) {
  45643. const backend = this.backend;
  45644. const { utils, device } = backend;
  45645. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  45646. const colorFormat = utils.getCurrentColorFormat( renderContext );
  45647. const sampleCount = this._getSampleCount( renderContext );
  45648. const descriptor = {
  45649. label: 'renderBundleEncoder',
  45650. colorFormats: [ colorFormat ],
  45651. depthStencilFormat,
  45652. sampleCount
  45653. };
  45654. return device.createRenderBundleEncoder( descriptor );
  45655. }
  45656. /**
  45657. * Creates a compute pipeline for the given compute node.
  45658. *
  45659. * @param {ComputePipeline} pipeline - The compute pipeline.
  45660. * @param {Array<BindGroup>} bindings - The bindings.
  45661. */
  45662. createComputePipeline( pipeline, bindings ) {
  45663. const backend = this.backend;
  45664. const device = backend.device;
  45665. const computeProgram = backend.get( pipeline.computeProgram ).module;
  45666. const pipelineGPU = backend.get( pipeline );
  45667. // bind group layouts
  45668. const bindGroupLayouts = [];
  45669. for ( const bindingsGroup of bindings ) {
  45670. const bindingsData = backend.get( bindingsGroup );
  45671. bindGroupLayouts.push( bindingsData.layout );
  45672. }
  45673. pipelineGPU.pipeline = device.createComputePipeline( {
  45674. compute: computeProgram,
  45675. layout: device.createPipelineLayout( {
  45676. bindGroupLayouts
  45677. } )
  45678. } );
  45679. }
  45680. /**
  45681. * Returns the blending state as a descriptor object required
  45682. * for the pipeline creation.
  45683. *
  45684. * @private
  45685. * @param {Material} material - The material.
  45686. * @return {Object} The blending state.
  45687. */
  45688. _getBlending( material ) {
  45689. let color, alpha;
  45690. const blending = material.blending;
  45691. const blendSrc = material.blendSrc;
  45692. const blendDst = material.blendDst;
  45693. const blendEquation = material.blendEquation;
  45694. if ( blending === CustomBlending ) {
  45695. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  45696. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  45697. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  45698. color = {
  45699. srcFactor: this._getBlendFactor( blendSrc ),
  45700. dstFactor: this._getBlendFactor( blendDst ),
  45701. operation: this._getBlendOperation( blendEquation )
  45702. };
  45703. alpha = {
  45704. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  45705. dstFactor: this._getBlendFactor( blendDstAlpha ),
  45706. operation: this._getBlendOperation( blendEquationAlpha )
  45707. };
  45708. } else {
  45709. const premultipliedAlpha = material.premultipliedAlpha;
  45710. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  45711. color = {
  45712. srcFactor: srcRGB,
  45713. dstFactor: dstRGB,
  45714. operation: GPUBlendOperation.Add
  45715. };
  45716. alpha = {
  45717. srcFactor: srcAlpha,
  45718. dstFactor: dstAlpha,
  45719. operation: GPUBlendOperation.Add
  45720. };
  45721. };
  45722. if ( premultipliedAlpha ) {
  45723. switch ( blending ) {
  45724. case NormalBlending:
  45725. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45726. break;
  45727. case AdditiveBlending:
  45728. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  45729. break;
  45730. case SubtractiveBlending:
  45731. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45732. break;
  45733. case MultiplyBlending:
  45734. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  45735. break;
  45736. }
  45737. } else {
  45738. switch ( blending ) {
  45739. case NormalBlending:
  45740. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  45741. break;
  45742. case AdditiveBlending:
  45743. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  45744. break;
  45745. case SubtractiveBlending:
  45746. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  45747. break;
  45748. case MultiplyBlending:
  45749. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  45750. break;
  45751. }
  45752. }
  45753. }
  45754. if ( color !== undefined && alpha !== undefined ) {
  45755. return { color, alpha };
  45756. } else {
  45757. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  45758. }
  45759. }
  45760. /**
  45761. * Returns the GPU blend factor which is required for the pipeline creation.
  45762. *
  45763. * @private
  45764. * @param {Number} blend - The blend factor as a three.js constant.
  45765. * @return {String} The GPU blend factor.
  45766. */
  45767. _getBlendFactor( blend ) {
  45768. let blendFactor;
  45769. switch ( blend ) {
  45770. case ZeroFactor:
  45771. blendFactor = GPUBlendFactor.Zero;
  45772. break;
  45773. case OneFactor:
  45774. blendFactor = GPUBlendFactor.One;
  45775. break;
  45776. case SrcColorFactor:
  45777. blendFactor = GPUBlendFactor.Src;
  45778. break;
  45779. case OneMinusSrcColorFactor:
  45780. blendFactor = GPUBlendFactor.OneMinusSrc;
  45781. break;
  45782. case SrcAlphaFactor:
  45783. blendFactor = GPUBlendFactor.SrcAlpha;
  45784. break;
  45785. case OneMinusSrcAlphaFactor:
  45786. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  45787. break;
  45788. case DstColorFactor:
  45789. blendFactor = GPUBlendFactor.Dst;
  45790. break;
  45791. case OneMinusDstColorFactor:
  45792. blendFactor = GPUBlendFactor.OneMinusDstColor;
  45793. break;
  45794. case DstAlphaFactor:
  45795. blendFactor = GPUBlendFactor.DstAlpha;
  45796. break;
  45797. case OneMinusDstAlphaFactor:
  45798. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  45799. break;
  45800. case SrcAlphaSaturateFactor:
  45801. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  45802. break;
  45803. case BlendColorFactor:
  45804. blendFactor = GPUBlendFactor.Constant;
  45805. break;
  45806. case OneMinusBlendColorFactor:
  45807. blendFactor = GPUBlendFactor.OneMinusConstant;
  45808. break;
  45809. default:
  45810. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  45811. }
  45812. return blendFactor;
  45813. }
  45814. /**
  45815. * Returns the GPU stencil compare function which is required for the pipeline creation.
  45816. *
  45817. * @private
  45818. * @param {Material} material - The material.
  45819. * @return {String} The GPU stencil compare function.
  45820. */
  45821. _getStencilCompare( material ) {
  45822. let stencilCompare;
  45823. const stencilFunc = material.stencilFunc;
  45824. switch ( stencilFunc ) {
  45825. case NeverStencilFunc:
  45826. stencilCompare = GPUCompareFunction.Never;
  45827. break;
  45828. case AlwaysStencilFunc:
  45829. stencilCompare = GPUCompareFunction.Always;
  45830. break;
  45831. case LessStencilFunc:
  45832. stencilCompare = GPUCompareFunction.Less;
  45833. break;
  45834. case LessEqualStencilFunc:
  45835. stencilCompare = GPUCompareFunction.LessEqual;
  45836. break;
  45837. case EqualStencilFunc:
  45838. stencilCompare = GPUCompareFunction.Equal;
  45839. break;
  45840. case GreaterEqualStencilFunc:
  45841. stencilCompare = GPUCompareFunction.GreaterEqual;
  45842. break;
  45843. case GreaterStencilFunc:
  45844. stencilCompare = GPUCompareFunction.Greater;
  45845. break;
  45846. case NotEqualStencilFunc:
  45847. stencilCompare = GPUCompareFunction.NotEqual;
  45848. break;
  45849. default:
  45850. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  45851. }
  45852. return stencilCompare;
  45853. }
  45854. /**
  45855. * Returns the GPU stencil operation which is required for the pipeline creation.
  45856. *
  45857. * @private
  45858. * @param {Number} op - A three.js constant defining the stencil operation.
  45859. * @return {String} The GPU stencil operation.
  45860. */
  45861. _getStencilOperation( op ) {
  45862. let stencilOperation;
  45863. switch ( op ) {
  45864. case KeepStencilOp:
  45865. stencilOperation = GPUStencilOperation.Keep;
  45866. break;
  45867. case ZeroStencilOp:
  45868. stencilOperation = GPUStencilOperation.Zero;
  45869. break;
  45870. case ReplaceStencilOp:
  45871. stencilOperation = GPUStencilOperation.Replace;
  45872. break;
  45873. case InvertStencilOp:
  45874. stencilOperation = GPUStencilOperation.Invert;
  45875. break;
  45876. case IncrementStencilOp:
  45877. stencilOperation = GPUStencilOperation.IncrementClamp;
  45878. break;
  45879. case DecrementStencilOp:
  45880. stencilOperation = GPUStencilOperation.DecrementClamp;
  45881. break;
  45882. case IncrementWrapStencilOp:
  45883. stencilOperation = GPUStencilOperation.IncrementWrap;
  45884. break;
  45885. case DecrementWrapStencilOp:
  45886. stencilOperation = GPUStencilOperation.DecrementWrap;
  45887. break;
  45888. default:
  45889. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  45890. }
  45891. return stencilOperation;
  45892. }
  45893. /**
  45894. * Returns the GPU blend operation which is required for the pipeline creation.
  45895. *
  45896. * @private
  45897. * @param {Number} blendEquation - A three.js constant defining the blend equation.
  45898. * @return {String} The GPU blend operation.
  45899. */
  45900. _getBlendOperation( blendEquation ) {
  45901. let blendOperation;
  45902. switch ( blendEquation ) {
  45903. case AddEquation:
  45904. blendOperation = GPUBlendOperation.Add;
  45905. break;
  45906. case SubtractEquation:
  45907. blendOperation = GPUBlendOperation.Subtract;
  45908. break;
  45909. case ReverseSubtractEquation:
  45910. blendOperation = GPUBlendOperation.ReverseSubtract;
  45911. break;
  45912. case MinEquation:
  45913. blendOperation = GPUBlendOperation.Min;
  45914. break;
  45915. case MaxEquation:
  45916. blendOperation = GPUBlendOperation.Max;
  45917. break;
  45918. default:
  45919. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  45920. }
  45921. return blendOperation;
  45922. }
  45923. /**
  45924. * Returns the primitive state as a descriptor object required
  45925. * for the pipeline creation.
  45926. *
  45927. * @private
  45928. * @param {Object3D} object - The 3D object.
  45929. * @param {BufferGeometry} geometry - The geometry.
  45930. * @param {Material} material - The material.
  45931. * @return {Object} The primitive state.
  45932. */
  45933. _getPrimitiveState( object, geometry, material ) {
  45934. const descriptor = {};
  45935. const utils = this.backend.utils;
  45936. descriptor.topology = utils.getPrimitiveTopology( object, material );
  45937. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  45938. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  45939. }
  45940. switch ( material.side ) {
  45941. case FrontSide:
  45942. descriptor.frontFace = GPUFrontFace.CCW;
  45943. descriptor.cullMode = GPUCullMode.Back;
  45944. break;
  45945. case BackSide:
  45946. descriptor.frontFace = GPUFrontFace.CCW;
  45947. descriptor.cullMode = GPUCullMode.Front;
  45948. break;
  45949. case DoubleSide:
  45950. descriptor.frontFace = GPUFrontFace.CCW;
  45951. descriptor.cullMode = GPUCullMode.None;
  45952. break;
  45953. default:
  45954. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  45955. break;
  45956. }
  45957. return descriptor;
  45958. }
  45959. /**
  45960. * Returns the GPU color write mask which is required for the pipeline creation.
  45961. *
  45962. * @private
  45963. * @param {Material} material - The material.
  45964. * @return {String} The GPU color write mask.
  45965. */
  45966. _getColorWriteMask( material ) {
  45967. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  45968. }
  45969. /**
  45970. * Returns the GPU depth compare function which is required for the pipeline creation.
  45971. *
  45972. * @private
  45973. * @param {Material} material - The material.
  45974. * @return {String} The GPU depth compare function.
  45975. */
  45976. _getDepthCompare( material ) {
  45977. let depthCompare;
  45978. if ( material.depthTest === false ) {
  45979. depthCompare = GPUCompareFunction.Always;
  45980. } else {
  45981. const depthFunc = material.depthFunc;
  45982. switch ( depthFunc ) {
  45983. case NeverDepth:
  45984. depthCompare = GPUCompareFunction.Never;
  45985. break;
  45986. case AlwaysDepth:
  45987. depthCompare = GPUCompareFunction.Always;
  45988. break;
  45989. case LessDepth:
  45990. depthCompare = GPUCompareFunction.Less;
  45991. break;
  45992. case LessEqualDepth:
  45993. depthCompare = GPUCompareFunction.LessEqual;
  45994. break;
  45995. case EqualDepth:
  45996. depthCompare = GPUCompareFunction.Equal;
  45997. break;
  45998. case GreaterEqualDepth:
  45999. depthCompare = GPUCompareFunction.GreaterEqual;
  46000. break;
  46001. case GreaterDepth:
  46002. depthCompare = GPUCompareFunction.Greater;
  46003. break;
  46004. case NotEqualDepth:
  46005. depthCompare = GPUCompareFunction.NotEqual;
  46006. break;
  46007. default:
  46008. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  46009. }
  46010. }
  46011. return depthCompare;
  46012. }
  46013. }
  46014. /*// debugger tools
  46015. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  46016. //*/
  46017. /**
  46018. * A backend implementation targeting WebGPU.
  46019. *
  46020. * @private
  46021. * @augments Backend
  46022. */
  46023. class WebGPUBackend extends Backend {
  46024. /**
  46025. * Constructs a new WebGPU backend.
  46026. *
  46027. * @param {Object} parameters - The configuration parameter.
  46028. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  46029. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  46030. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  46031. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  46032. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  46033. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0 to overwrite the default.
  46034. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  46035. * @param {Boolean} [parameters.trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  46036. * @param {String} [parameters.powerPreference=undefined] - The power preference.
  46037. * @param {Object} [parameters.requiredLimits=undefined] - Specifies the limits that are required by the device request. The request will fail if the adapter cannot provide these limits.
  46038. * @param {GPUDevice} [parameters.device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  46039. * @param {Number} [parameters.outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  46040. */
  46041. constructor( parameters = {} ) {
  46042. super( parameters );
  46043. /**
  46044. * This flag can be used for type testing.
  46045. *
  46046. * @type {Boolean}
  46047. * @readonly
  46048. * @default true
  46049. */
  46050. this.isWebGPUBackend = true;
  46051. // some parameters require default values other than "undefined"
  46052. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  46053. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  46054. /**
  46055. * Whether to track timestamps with a Timestamp Query API or not.
  46056. *
  46057. * @type {Boolean}
  46058. * @default false
  46059. */
  46060. this.trackTimestamp = ( parameters.trackTimestamp === true );
  46061. /**
  46062. * A reference to the device.
  46063. *
  46064. * @type {GPUDevice?}
  46065. * @default null
  46066. */
  46067. this.device = null;
  46068. /**
  46069. * A reference to the context.
  46070. *
  46071. * @type {GPUCanvasContext?}
  46072. * @default null
  46073. */
  46074. this.context = null;
  46075. /**
  46076. * A reference to the color attachment of the default framebuffer.
  46077. *
  46078. * @type {GPUTexture?}
  46079. * @default null
  46080. */
  46081. this.colorBuffer = null;
  46082. /**
  46083. * A reference to the default render pass descriptor.
  46084. *
  46085. * @type {Object?}
  46086. * @default null
  46087. */
  46088. this.defaultRenderPassdescriptor = null;
  46089. /**
  46090. * A reference to a backend module holding common utility functions.
  46091. *
  46092. * @type {WebGPUUtils}
  46093. */
  46094. this.utils = new WebGPUUtils( this );
  46095. /**
  46096. * A reference to a backend module holding shader attribute-related
  46097. * utility functions.
  46098. *
  46099. * @type {WebGPUAttributeUtils}
  46100. */
  46101. this.attributeUtils = new WebGPUAttributeUtils( this );
  46102. /**
  46103. * A reference to a backend module holding shader binding-related
  46104. * utility functions.
  46105. *
  46106. * @type {WebGPUBindingUtils}
  46107. */
  46108. this.bindingUtils = new WebGPUBindingUtils( this );
  46109. /**
  46110. * A reference to a backend module holding shader pipeline-related
  46111. * utility functions.
  46112. *
  46113. * @type {WebGPUPipelineUtils}
  46114. */
  46115. this.pipelineUtils = new WebGPUPipelineUtils( this );
  46116. /**
  46117. * A reference to a backend module holding shader texture-related
  46118. * utility functions.
  46119. *
  46120. * @type {WebGPUTextureUtils}
  46121. */
  46122. this.textureUtils = new WebGPUTextureUtils( this );
  46123. /**
  46124. * A map that manages the resolve buffers for occlusion queries.
  46125. *
  46126. * @type {Map<Number,GPUBuffer>}
  46127. */
  46128. this.occludedResolveCache = new Map();
  46129. }
  46130. /**
  46131. * Initializes the backend so it is ready for usage.
  46132. *
  46133. * @async
  46134. * @param {Renderer} renderer - The renderer.
  46135. * @return {Promise} A Promise that resolves when the backend has been initialized.
  46136. */
  46137. async init( renderer ) {
  46138. await super.init( renderer );
  46139. //
  46140. const parameters = this.parameters;
  46141. // create the device if it is not passed with parameters
  46142. let device;
  46143. if ( parameters.device === undefined ) {
  46144. const adapterOptions = {
  46145. powerPreference: parameters.powerPreference
  46146. };
  46147. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  46148. if ( adapter === null ) {
  46149. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  46150. }
  46151. // feature support
  46152. const features = Object.values( GPUFeatureName );
  46153. const supportedFeatures = [];
  46154. for ( const name of features ) {
  46155. if ( adapter.features.has( name ) ) {
  46156. supportedFeatures.push( name );
  46157. }
  46158. }
  46159. const deviceDescriptor = {
  46160. requiredFeatures: supportedFeatures,
  46161. requiredLimits: parameters.requiredLimits
  46162. };
  46163. device = await adapter.requestDevice( deviceDescriptor );
  46164. } else {
  46165. device = parameters.device;
  46166. }
  46167. device.lost.then( ( info ) => {
  46168. const deviceLossInfo = {
  46169. api: 'WebGPU',
  46170. message: info.message || 'Unknown reason',
  46171. reason: info.reason || null,
  46172. originalEvent: info
  46173. };
  46174. renderer.onDeviceLost( deviceLossInfo );
  46175. } );
  46176. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  46177. this.device = device;
  46178. this.context = context;
  46179. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  46180. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  46181. this.context.configure( {
  46182. device: this.device,
  46183. format: this.utils.getPreferredCanvasFormat(),
  46184. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  46185. alphaMode: alphaMode
  46186. } );
  46187. this.updateSize();
  46188. }
  46189. /**
  46190. * The coordinate system of the backend.
  46191. *
  46192. * @type {Number}
  46193. * @readonly
  46194. */
  46195. get coordinateSystem() {
  46196. return WebGPUCoordinateSystem;
  46197. }
  46198. /**
  46199. * This method performs a readback operation by moving buffer data from
  46200. * a storage buffer attribute from the GPU to the CPU.
  46201. *
  46202. * @async
  46203. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  46204. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  46205. */
  46206. async getArrayBufferAsync( attribute ) {
  46207. return await this.attributeUtils.getArrayBufferAsync( attribute );
  46208. }
  46209. /**
  46210. * Returns the backend's rendering context.
  46211. *
  46212. * @return {GPUCanvasContext} The rendering context.
  46213. */
  46214. getContext() {
  46215. return this.context;
  46216. }
  46217. /**
  46218. * Returns the default render pass descriptor.
  46219. *
  46220. * In WebGPU, the default framebuffer must be configured
  46221. * like custom framebuffers so the backend needs a render
  46222. * pass descriptor even when rendering directly to screen.
  46223. *
  46224. * @private
  46225. * @return {Object} The render pass descriptor.
  46226. */
  46227. _getDefaultRenderPassDescriptor() {
  46228. let descriptor = this.defaultRenderPassdescriptor;
  46229. if ( descriptor === null ) {
  46230. const renderer = this.renderer;
  46231. descriptor = {
  46232. colorAttachments: [ {
  46233. view: null
  46234. } ],
  46235. };
  46236. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  46237. descriptor.depthStencilAttachment = {
  46238. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  46239. };
  46240. }
  46241. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46242. if ( this.renderer.samples > 0 ) {
  46243. colorAttachment.view = this.colorBuffer.createView();
  46244. } else {
  46245. colorAttachment.resolveTarget = undefined;
  46246. }
  46247. this.defaultRenderPassdescriptor = descriptor;
  46248. }
  46249. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46250. if ( this.renderer.samples > 0 ) {
  46251. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  46252. } else {
  46253. colorAttachment.view = this.context.getCurrentTexture().createView();
  46254. }
  46255. return descriptor;
  46256. }
  46257. /**
  46258. * Returns the render pass descriptor for the given render context.
  46259. *
  46260. * @private
  46261. * @param {RenderContext} renderContext - The render context.
  46262. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  46263. * @return {Object} The render pass descriptor.
  46264. */
  46265. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  46266. const renderTarget = renderContext.renderTarget;
  46267. const renderTargetData = this.get( renderTarget );
  46268. let descriptors = renderTargetData.descriptors;
  46269. if ( descriptors === undefined ||
  46270. renderTargetData.width !== renderTarget.width ||
  46271. renderTargetData.height !== renderTarget.height ||
  46272. renderTargetData.dimensions !== renderTarget.dimensions ||
  46273. renderTargetData.activeMipmapLevel !== renderTarget.activeMipmapLevel ||
  46274. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  46275. renderTargetData.samples !== renderTarget.samples ||
  46276. renderTargetData.loadOp !== colorAttachmentsConfig.loadOp
  46277. ) {
  46278. descriptors = {};
  46279. renderTargetData.descriptors = descriptors;
  46280. // dispose
  46281. const onDispose = () => {
  46282. renderTarget.removeEventListener( 'dispose', onDispose );
  46283. this.delete( renderTarget );
  46284. };
  46285. renderTarget.addEventListener( 'dispose', onDispose );
  46286. }
  46287. const cacheKey = renderContext.getCacheKey();
  46288. let descriptor = descriptors[ cacheKey ];
  46289. if ( descriptor === undefined ) {
  46290. const textures = renderContext.textures;
  46291. const colorAttachments = [];
  46292. let sliceIndex;
  46293. for ( let i = 0; i < textures.length; i ++ ) {
  46294. const textureData = this.get( textures[ i ] );
  46295. const viewDescriptor = {
  46296. label: `colorAttachment_${ i }`,
  46297. baseMipLevel: renderContext.activeMipmapLevel,
  46298. mipLevelCount: 1,
  46299. baseArrayLayer: renderContext.activeCubeFace,
  46300. arrayLayerCount: 1,
  46301. dimension: GPUTextureViewDimension.TwoD
  46302. };
  46303. if ( renderTarget.isRenderTarget3D ) {
  46304. sliceIndex = renderContext.activeCubeFace;
  46305. viewDescriptor.baseArrayLayer = 0;
  46306. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  46307. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  46308. } else if ( renderTarget.isRenderTargetArray ) {
  46309. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  46310. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  46311. }
  46312. const textureView = textureData.texture.createView( viewDescriptor );
  46313. let view, resolveTarget;
  46314. if ( textureData.msaaTexture !== undefined ) {
  46315. view = textureData.msaaTexture.createView();
  46316. resolveTarget = textureView;
  46317. } else {
  46318. view = textureView;
  46319. resolveTarget = undefined;
  46320. }
  46321. colorAttachments.push( {
  46322. view,
  46323. depthSlice: sliceIndex,
  46324. resolveTarget,
  46325. loadOp: GPULoadOp.Load,
  46326. storeOp: GPUStoreOp.Store,
  46327. ...colorAttachmentsConfig
  46328. } );
  46329. }
  46330. descriptor = {
  46331. colorAttachments,
  46332. };
  46333. if ( renderContext.depth ) {
  46334. const depthTextureData = this.get( renderContext.depthTexture );
  46335. const depthStencilAttachment = {
  46336. view: depthTextureData.texture.createView()
  46337. };
  46338. descriptor.depthStencilAttachment = depthStencilAttachment;
  46339. }
  46340. descriptors[ cacheKey ] = descriptor;
  46341. renderTargetData.width = renderTarget.width;
  46342. renderTargetData.height = renderTarget.height;
  46343. renderTargetData.samples = renderTarget.samples;
  46344. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  46345. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  46346. renderTargetData.dimensions = renderTarget.dimensions;
  46347. renderTargetData.depthSlice = sliceIndex;
  46348. renderTargetData.loadOp = colorAttachments[ 0 ].loadOp;
  46349. }
  46350. return descriptor;
  46351. }
  46352. /**
  46353. * This method is executed at the beginning of a render call and prepares
  46354. * the WebGPU state for upcoming render calls
  46355. *
  46356. * @param {RenderContext} renderContext - The render context.
  46357. */
  46358. beginRender( renderContext ) {
  46359. const renderContextData = this.get( renderContext );
  46360. const device = this.device;
  46361. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46362. let occlusionQuerySet;
  46363. if ( occlusionQueryCount > 0 ) {
  46364. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  46365. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  46366. // Get a reference to the array of objects with queries. The renderContextData property
  46367. // can be changed by another render pass before the buffer.mapAsyc() completes.
  46368. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  46369. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  46370. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  46371. //
  46372. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  46373. renderContextData.occlusionQuerySet = occlusionQuerySet;
  46374. renderContextData.occlusionQueryIndex = 0;
  46375. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  46376. renderContextData.lastOcclusionObject = null;
  46377. }
  46378. let descriptor;
  46379. if ( renderContext.textures === null ) {
  46380. descriptor = this._getDefaultRenderPassDescriptor();
  46381. } else {
  46382. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  46383. }
  46384. this.initTimestampQuery( renderContext, descriptor );
  46385. descriptor.occlusionQuerySet = occlusionQuerySet;
  46386. const depthStencilAttachment = descriptor.depthStencilAttachment;
  46387. if ( renderContext.textures !== null ) {
  46388. const colorAttachments = descriptor.colorAttachments;
  46389. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  46390. const colorAttachment = colorAttachments[ i ];
  46391. if ( renderContext.clearColor ) {
  46392. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  46393. colorAttachment.loadOp = GPULoadOp.Clear;
  46394. colorAttachment.storeOp = GPUStoreOp.Store;
  46395. } else {
  46396. colorAttachment.loadOp = GPULoadOp.Load;
  46397. colorAttachment.storeOp = GPUStoreOp.Store;
  46398. }
  46399. }
  46400. } else {
  46401. const colorAttachment = descriptor.colorAttachments[ 0 ];
  46402. if ( renderContext.clearColor ) {
  46403. colorAttachment.clearValue = renderContext.clearColorValue;
  46404. colorAttachment.loadOp = GPULoadOp.Clear;
  46405. colorAttachment.storeOp = GPUStoreOp.Store;
  46406. } else {
  46407. colorAttachment.loadOp = GPULoadOp.Load;
  46408. colorAttachment.storeOp = GPUStoreOp.Store;
  46409. }
  46410. }
  46411. //
  46412. if ( renderContext.depth ) {
  46413. if ( renderContext.clearDepth ) {
  46414. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  46415. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  46416. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46417. } else {
  46418. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46419. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46420. }
  46421. }
  46422. if ( renderContext.stencil ) {
  46423. if ( renderContext.clearStencil ) {
  46424. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  46425. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  46426. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46427. } else {
  46428. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46429. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46430. }
  46431. }
  46432. //
  46433. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  46434. const currentPass = encoder.beginRenderPass( descriptor );
  46435. //
  46436. renderContextData.descriptor = descriptor;
  46437. renderContextData.encoder = encoder;
  46438. renderContextData.currentPass = currentPass;
  46439. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  46440. renderContextData.renderBundles = [];
  46441. //
  46442. if ( renderContext.viewport ) {
  46443. this.updateViewport( renderContext );
  46444. }
  46445. if ( renderContext.scissor ) {
  46446. const { x, y, width, height } = renderContext.scissorValue;
  46447. currentPass.setScissorRect( x, y, width, height );
  46448. }
  46449. }
  46450. /**
  46451. * This method is executed at the end of a render call and finalizes work
  46452. * after draw calls.
  46453. *
  46454. * @param {RenderContext} renderContext - The render context.
  46455. */
  46456. finishRender( renderContext ) {
  46457. const renderContextData = this.get( renderContext );
  46458. const occlusionQueryCount = renderContext.occlusionQueryCount;
  46459. if ( renderContextData.renderBundles.length > 0 ) {
  46460. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  46461. }
  46462. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  46463. renderContextData.currentPass.endOcclusionQuery();
  46464. }
  46465. renderContextData.currentPass.end();
  46466. if ( occlusionQueryCount > 0 ) {
  46467. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  46468. //
  46469. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  46470. if ( queryResolveBuffer === undefined ) {
  46471. queryResolveBuffer = this.device.createBuffer(
  46472. {
  46473. size: bufferSize,
  46474. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  46475. }
  46476. );
  46477. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  46478. }
  46479. //
  46480. const readBuffer = this.device.createBuffer(
  46481. {
  46482. size: bufferSize,
  46483. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46484. }
  46485. );
  46486. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  46487. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  46488. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  46489. renderContextData.occlusionQueryBuffer = readBuffer;
  46490. //
  46491. this.resolveOccludedAsync( renderContext );
  46492. }
  46493. this.prepareTimestampBuffer( renderContext, renderContextData.encoder );
  46494. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  46495. //
  46496. if ( renderContext.textures !== null ) {
  46497. const textures = renderContext.textures;
  46498. for ( let i = 0; i < textures.length; i ++ ) {
  46499. const texture = textures[ i ];
  46500. if ( texture.generateMipmaps === true ) {
  46501. this.textureUtils.generateMipmaps( texture );
  46502. }
  46503. }
  46504. }
  46505. }
  46506. /**
  46507. * Returns `true` if the given 3D object is fully occluded by other
  46508. * 3D objects in the scene.
  46509. *
  46510. * @param {RenderContext} renderContext - The render context.
  46511. * @param {Object3D} object - The 3D object to test.
  46512. * @return {Boolean} Whether the 3D object is fully occluded or not.
  46513. */
  46514. isOccluded( renderContext, object ) {
  46515. const renderContextData = this.get( renderContext );
  46516. return renderContextData.occluded && renderContextData.occluded.has( object );
  46517. }
  46518. /**
  46519. * This method processes the result of occlusion queries and writes it
  46520. * into render context data.
  46521. *
  46522. * @async
  46523. * @param {RenderContext} renderContext - The render context.
  46524. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  46525. */
  46526. async resolveOccludedAsync( renderContext ) {
  46527. const renderContextData = this.get( renderContext );
  46528. // handle occlusion query results
  46529. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  46530. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  46531. const occluded = new WeakSet();
  46532. renderContextData.currentOcclusionQueryObjects = null;
  46533. renderContextData.currentOcclusionQueryBuffer = null;
  46534. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  46535. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  46536. const results = new BigUint64Array( buffer );
  46537. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  46538. if ( results[ i ] === BigInt( 0 ) ) {
  46539. occluded.add( currentOcclusionQueryObjects[ i ] );
  46540. }
  46541. }
  46542. currentOcclusionQueryBuffer.destroy();
  46543. renderContextData.occluded = occluded;
  46544. }
  46545. }
  46546. /**
  46547. * Updates the viewport with the values from the given render context.
  46548. *
  46549. * @param {RenderContext} renderContext - The render context.
  46550. */
  46551. updateViewport( renderContext ) {
  46552. const { currentPass } = this.get( renderContext );
  46553. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  46554. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  46555. }
  46556. /**
  46557. * Performs a clear operation.
  46558. *
  46559. * @param {Boolean} color - Whether the color buffer should be cleared or not.
  46560. * @param {Boolean} depth - Whether the depth buffer should be cleared or not.
  46561. * @param {Boolean} stencil - Whether the stencil buffer should be cleared or not.
  46562. * @param {RenderContext?} [renderTargetContext=null] - The render context of the current set render target.
  46563. */
  46564. clear( color, depth, stencil, renderTargetContext = null ) {
  46565. const device = this.device;
  46566. const renderer = this.renderer;
  46567. let colorAttachments = [];
  46568. let depthStencilAttachment;
  46569. let clearValue;
  46570. let supportsDepth;
  46571. let supportsStencil;
  46572. if ( color ) {
  46573. const clearColor = this.getClearColor();
  46574. if ( this.renderer.alpha === true ) {
  46575. // premultiply alpha
  46576. const a = clearColor.a;
  46577. clearValue = { r: clearColor.r * a, g: clearColor.g * a, b: clearColor.b * a, a: a };
  46578. } else {
  46579. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  46580. }
  46581. }
  46582. if ( renderTargetContext === null ) {
  46583. supportsDepth = renderer.depth;
  46584. supportsStencil = renderer.stencil;
  46585. const descriptor = this._getDefaultRenderPassDescriptor();
  46586. if ( color ) {
  46587. colorAttachments = descriptor.colorAttachments;
  46588. const colorAttachment = colorAttachments[ 0 ];
  46589. colorAttachment.clearValue = clearValue;
  46590. colorAttachment.loadOp = GPULoadOp.Clear;
  46591. colorAttachment.storeOp = GPUStoreOp.Store;
  46592. }
  46593. if ( supportsDepth || supportsStencil ) {
  46594. depthStencilAttachment = descriptor.depthStencilAttachment;
  46595. }
  46596. } else {
  46597. supportsDepth = renderTargetContext.depth;
  46598. supportsStencil = renderTargetContext.stencil;
  46599. if ( color ) {
  46600. const descriptor = this._getRenderPassDescriptor( renderTargetContext, { loadOp: GPULoadOp.Clear, clearValue } );
  46601. colorAttachments = descriptor.colorAttachments;
  46602. }
  46603. if ( supportsDepth || supportsStencil ) {
  46604. const depthTextureData = this.get( renderTargetContext.depthTexture );
  46605. depthStencilAttachment = {
  46606. view: depthTextureData.texture.createView()
  46607. };
  46608. }
  46609. }
  46610. //
  46611. if ( supportsDepth ) {
  46612. if ( depth ) {
  46613. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  46614. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  46615. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46616. } else {
  46617. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  46618. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  46619. }
  46620. }
  46621. //
  46622. if ( supportsStencil ) {
  46623. if ( stencil ) {
  46624. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  46625. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  46626. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46627. } else {
  46628. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  46629. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  46630. }
  46631. }
  46632. //
  46633. const encoder = device.createCommandEncoder( { label: 'clear' } );
  46634. const currentPass = encoder.beginRenderPass( {
  46635. colorAttachments,
  46636. depthStencilAttachment
  46637. } );
  46638. currentPass.end();
  46639. device.queue.submit( [ encoder.finish() ] );
  46640. }
  46641. // compute
  46642. /**
  46643. * This method is executed at the beginning of a compute call and
  46644. * prepares the state for upcoming compute tasks.
  46645. *
  46646. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46647. */
  46648. beginCompute( computeGroup ) {
  46649. const groupGPU = this.get( computeGroup );
  46650. const descriptor = {
  46651. label: 'computeGroup_' + computeGroup.id
  46652. };
  46653. this.initTimestampQuery( computeGroup, descriptor );
  46654. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  46655. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  46656. }
  46657. /**
  46658. * Executes a compute command for the given compute node.
  46659. *
  46660. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  46661. * @param {Node} computeNode - The compute node.
  46662. * @param {Array<BindGroup>} bindings - The bindings.
  46663. * @param {ComputePipeline} pipeline - The compute pipeline.
  46664. */
  46665. compute( computeGroup, computeNode, bindings, pipeline ) {
  46666. const { passEncoderGPU } = this.get( computeGroup );
  46667. // pipeline
  46668. const pipelineGPU = this.get( pipeline ).pipeline;
  46669. passEncoderGPU.setPipeline( pipelineGPU );
  46670. // bind groups
  46671. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  46672. const bindGroup = bindings[ i ];
  46673. const bindingsData = this.get( bindGroup );
  46674. passEncoderGPU.setBindGroup( i, bindingsData.group );
  46675. }
  46676. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  46677. const computeNodeData = this.get( computeNode );
  46678. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  46679. const { dispatchSize } = computeNodeData;
  46680. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  46681. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  46682. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  46683. } else {
  46684. dispatchSize.x = computeNode.dispatchCount;
  46685. }
  46686. passEncoderGPU.dispatchWorkgroups(
  46687. dispatchSize.x,
  46688. dispatchSize.y,
  46689. dispatchSize.z
  46690. );
  46691. }
  46692. /**
  46693. * This method is executed at the end of a compute call and
  46694. * finalizes work after compute tasks.
  46695. *
  46696. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46697. */
  46698. finishCompute( computeGroup ) {
  46699. const groupData = this.get( computeGroup );
  46700. groupData.passEncoderGPU.end();
  46701. this.prepareTimestampBuffer( computeGroup, groupData.cmdEncoderGPU );
  46702. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  46703. }
  46704. /**
  46705. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  46706. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  46707. *
  46708. * @async
  46709. * @return {Promise} A Promise that resolves when synchronization has been finished.
  46710. */
  46711. async waitForGPU() {
  46712. await this.device.queue.onSubmittedWorkDone();
  46713. }
  46714. // render object
  46715. /**
  46716. * Executes a draw command for the given render object.
  46717. *
  46718. * @param {RenderObject} renderObject - The render object to draw.
  46719. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  46720. */
  46721. draw( renderObject, info ) {
  46722. const { object, context, pipeline } = renderObject;
  46723. const bindings = renderObject.getBindings();
  46724. const renderContextData = this.get( context );
  46725. const pipelineGPU = this.get( pipeline ).pipeline;
  46726. const currentSets = renderContextData.currentSets;
  46727. const passEncoderGPU = renderContextData.currentPass;
  46728. const drawParams = renderObject.getDrawParameters();
  46729. if ( drawParams === null ) return;
  46730. // pipeline
  46731. if ( currentSets.pipeline !== pipelineGPU ) {
  46732. passEncoderGPU.setPipeline( pipelineGPU );
  46733. currentSets.pipeline = pipelineGPU;
  46734. }
  46735. // bind groups
  46736. const currentBindingGroups = currentSets.bindingGroups;
  46737. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  46738. const bindGroup = bindings[ i ];
  46739. const bindingsData = this.get( bindGroup );
  46740. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  46741. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  46742. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  46743. }
  46744. }
  46745. // attributes
  46746. const index = renderObject.getIndex();
  46747. const hasIndex = ( index !== null );
  46748. // index
  46749. if ( hasIndex === true ) {
  46750. if ( currentSets.index !== index ) {
  46751. const buffer = this.get( index ).buffer;
  46752. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  46753. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  46754. currentSets.index = index;
  46755. }
  46756. }
  46757. // vertex buffers
  46758. const vertexBuffers = renderObject.getVertexBuffers();
  46759. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  46760. const vertexBuffer = vertexBuffers[ i ];
  46761. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  46762. const buffer = this.get( vertexBuffer ).buffer;
  46763. passEncoderGPU.setVertexBuffer( i, buffer );
  46764. currentSets.attributes[ i ] = vertexBuffer;
  46765. }
  46766. }
  46767. // occlusion queries - handle multiple consecutive draw calls for an object
  46768. if ( renderContextData.occlusionQuerySet !== undefined ) {
  46769. const lastObject = renderContextData.lastOcclusionObject;
  46770. if ( lastObject !== object ) {
  46771. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  46772. passEncoderGPU.endOcclusionQuery();
  46773. renderContextData.occlusionQueryIndex ++;
  46774. }
  46775. if ( object.occlusionTest === true ) {
  46776. passEncoderGPU.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  46777. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  46778. }
  46779. renderContextData.lastOcclusionObject = object;
  46780. }
  46781. }
  46782. // draw
  46783. const draw = () => {
  46784. if ( object.isBatchedMesh === true ) {
  46785. const starts = object._multiDrawStarts;
  46786. const counts = object._multiDrawCounts;
  46787. const drawCount = object._multiDrawCount;
  46788. const drawInstances = object._multiDrawInstances;
  46789. for ( let i = 0; i < drawCount; i ++ ) {
  46790. const count = drawInstances ? drawInstances[ i ] : 1;
  46791. const firstInstance = count > 1 ? 0 : i;
  46792. if ( hasIndex === true ) {
  46793. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  46794. } else {
  46795. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  46796. }
  46797. }
  46798. } else if ( hasIndex === true ) {
  46799. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  46800. const indirect = renderObject.getIndirect();
  46801. if ( indirect !== null ) {
  46802. const buffer = this.get( indirect ).buffer;
  46803. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  46804. } else {
  46805. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  46806. }
  46807. info.update( object, indexCount, instanceCount );
  46808. } else {
  46809. const { vertexCount, instanceCount, firstVertex } = drawParams;
  46810. const indirect = renderObject.getIndirect();
  46811. if ( indirect !== null ) {
  46812. const buffer = this.get( indirect ).buffer;
  46813. passEncoderGPU.drawIndirect( buffer, 0 );
  46814. } else {
  46815. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  46816. }
  46817. info.update( object, vertexCount, instanceCount );
  46818. }
  46819. };
  46820. if ( renderObject.camera.isArrayCamera ) {
  46821. const cameraData = this.get( renderObject.camera );
  46822. const cameras = renderObject.camera.cameras;
  46823. if ( cameraData.indexesGPU === undefined ) {
  46824. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  46825. const bindingsData = this.get( cameraIndex );
  46826. const indexesGPU = [];
  46827. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  46828. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46829. data[ 0 ] = i;
  46830. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  46831. indexesGPU.push( bindGroupIndex );
  46832. }
  46833. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  46834. cameraData.cameraIndex = cameraIndex;
  46835. }
  46836. const pixelRatio = this.renderer.getPixelRatio();
  46837. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46838. const subCamera = cameras[ i ];
  46839. if ( object.layers.test( subCamera.layers ) ) {
  46840. const vp = subCamera.viewport;
  46841. passEncoderGPU.setViewport(
  46842. Math.floor( vp.x * pixelRatio ),
  46843. Math.floor( vp.y * pixelRatio ),
  46844. Math.floor( vp.width * pixelRatio ),
  46845. Math.floor( vp.height * pixelRatio ),
  46846. context.viewportValue.minDepth,
  46847. context.viewportValue.maxDepth
  46848. );
  46849. passEncoderGPU.setBindGroup( cameraData.cameraIndex.index, cameraData.indexesGPU[ i ] );
  46850. draw();
  46851. }
  46852. }
  46853. } else {
  46854. draw();
  46855. }
  46856. }
  46857. // cache key
  46858. /**
  46859. * Returns `true` if the render pipeline requires an update.
  46860. *
  46861. * @param {RenderObject} renderObject - The render object.
  46862. * @return {Boolean} Whether the render pipeline requires an update or not.
  46863. */
  46864. needsRenderUpdate( renderObject ) {
  46865. const data = this.get( renderObject );
  46866. const { object, material } = renderObject;
  46867. const utils = this.utils;
  46868. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  46869. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  46870. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  46871. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  46872. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  46873. let needsUpdate = false;
  46874. if ( data.material !== material || data.materialVersion !== material.version ||
  46875. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  46876. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  46877. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  46878. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  46879. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  46880. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  46881. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  46882. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  46883. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  46884. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  46885. data.primitiveTopology !== primitiveTopology ||
  46886. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  46887. ) {
  46888. data.material = material; data.materialVersion = material.version;
  46889. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  46890. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  46891. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  46892. data.colorWrite = material.colorWrite;
  46893. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  46894. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  46895. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  46896. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  46897. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  46898. data.sampleCount = sampleCount;
  46899. data.colorSpace = colorSpace;
  46900. data.colorFormat = colorFormat;
  46901. data.depthStencilFormat = depthStencilFormat;
  46902. data.primitiveTopology = primitiveTopology;
  46903. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  46904. needsUpdate = true;
  46905. }
  46906. return needsUpdate;
  46907. }
  46908. /**
  46909. * Returns a cache key that is used to identify render pipelines.
  46910. *
  46911. * @param {RenderObject} renderObject - The render object.
  46912. * @return {String} The cache key.
  46913. */
  46914. getRenderCacheKey( renderObject ) {
  46915. const { object, material } = renderObject;
  46916. const utils = this.utils;
  46917. const renderContext = renderObject.context;
  46918. return [
  46919. material.transparent, material.blending, material.premultipliedAlpha,
  46920. material.blendSrc, material.blendDst, material.blendEquation,
  46921. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  46922. material.colorWrite,
  46923. material.depthWrite, material.depthTest, material.depthFunc,
  46924. material.stencilWrite, material.stencilFunc,
  46925. material.stencilFail, material.stencilZFail, material.stencilZPass,
  46926. material.stencilFuncMask, material.stencilWriteMask,
  46927. material.side,
  46928. utils.getSampleCountRenderContext( renderContext ),
  46929. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  46930. utils.getPrimitiveTopology( object, material ),
  46931. renderObject.getGeometryCacheKey(),
  46932. renderObject.clippingContextCacheKey
  46933. ].join();
  46934. }
  46935. // textures
  46936. /**
  46937. * Creates a GPU sampler for the given texture.
  46938. *
  46939. * @param {Texture} texture - The texture to create the sampler for.
  46940. */
  46941. createSampler( texture ) {
  46942. this.textureUtils.createSampler( texture );
  46943. }
  46944. /**
  46945. * Destroys the GPU sampler for the given texture.
  46946. *
  46947. * @param {Texture} texture - The texture to destroy the sampler for.
  46948. */
  46949. destroySampler( texture ) {
  46950. this.textureUtils.destroySampler( texture );
  46951. }
  46952. /**
  46953. * Creates a default texture for the given texture that can be used
  46954. * as a placeholder until the actual texture is ready for usage.
  46955. *
  46956. * @param {Texture} texture - The texture to create a default texture for.
  46957. */
  46958. createDefaultTexture( texture ) {
  46959. this.textureUtils.createDefaultTexture( texture );
  46960. }
  46961. /**
  46962. * Defines a texture on the GPU for the given texture object.
  46963. *
  46964. * @param {Texture} texture - The texture.
  46965. * @param {Object} [options={}] - Optional configuration parameter.
  46966. */
  46967. createTexture( texture, options ) {
  46968. this.textureUtils.createTexture( texture, options );
  46969. }
  46970. /**
  46971. * Uploads the updated texture data to the GPU.
  46972. *
  46973. * @param {Texture} texture - The texture.
  46974. * @param {Object} [options={}] - Optional configuration parameter.
  46975. */
  46976. updateTexture( texture, options ) {
  46977. this.textureUtils.updateTexture( texture, options );
  46978. }
  46979. /**
  46980. * Generates mipmaps for the given texture.
  46981. *
  46982. * @param {Texture} texture - The texture.
  46983. */
  46984. generateMipmaps( texture ) {
  46985. this.textureUtils.generateMipmaps( texture );
  46986. }
  46987. /**
  46988. * Destroys the GPU data for the given texture object.
  46989. *
  46990. * @param {Texture} texture - The texture.
  46991. */
  46992. destroyTexture( texture ) {
  46993. this.textureUtils.destroyTexture( texture );
  46994. }
  46995. /**
  46996. * Returns texture data as a typed array.
  46997. *
  46998. * @async
  46999. * @param {Texture} texture - The texture to copy.
  47000. * @param {Number} x - The x coordinate of the copy origin.
  47001. * @param {Number} y - The y coordinate of the copy origin.
  47002. * @param {Number} width - The width of the copy.
  47003. * @param {Number} height - The height of the copy.
  47004. * @param {Number} faceIndex - The face index.
  47005. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47006. */
  47007. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47008. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  47009. }
  47010. /**
  47011. * Inits a time stamp query for the given render context.
  47012. *
  47013. * @param {RenderContext} renderContext - The render context.
  47014. * @param {Object} descriptor - The query descriptor.
  47015. */
  47016. initTimestampQuery( renderContext, descriptor ) {
  47017. if ( ! this.trackTimestamp ) return;
  47018. const renderContextData = this.get( renderContext );
  47019. // init query set if not exists
  47020. if ( ! renderContextData.timestampQuerySet ) {
  47021. const type = renderContext.isComputeNode ? 'compute' : 'render';
  47022. renderContextData.timestampQuerySet = this.device.createQuerySet( { type: 'timestamp', count: 2, label: `timestamp_${type}_${renderContext.id}` } );
  47023. }
  47024. // augment descriptor
  47025. descriptor.timestampWrites = {
  47026. querySet: renderContextData.timestampQuerySet,
  47027. beginningOfPassWriteIndex: 0, // Write timestamp in index 0 when pass begins.
  47028. endOfPassWriteIndex: 1, // Write timestamp in index 1 when pass ends.
  47029. };
  47030. }
  47031. /**
  47032. * Prepares the timestamp buffer.
  47033. *
  47034. * @param {RenderContext} renderContext - The render context.
  47035. * @param {GPUCommandEncoder} encoder - The command encoder.
  47036. */
  47037. prepareTimestampBuffer( renderContext, encoder ) {
  47038. if ( ! this.trackTimestamp ) return;
  47039. const renderContextData = this.get( renderContext );
  47040. const size = 2 * BigUint64Array.BYTES_PER_ELEMENT;
  47041. if ( renderContextData.currentTimestampQueryBuffers === undefined ) {
  47042. renderContextData.currentTimestampQueryBuffers = {
  47043. resolveBuffer: this.device.createBuffer( {
  47044. label: 'timestamp resolve buffer',
  47045. size: size,
  47046. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC,
  47047. } ),
  47048. resultBuffer: this.device.createBuffer( {
  47049. label: 'timestamp result buffer',
  47050. size: size,
  47051. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ,
  47052. } )
  47053. };
  47054. }
  47055. const { resolveBuffer, resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  47056. encoder.resolveQuerySet( renderContextData.timestampQuerySet, 0, 2, resolveBuffer, 0 );
  47057. if ( resultBuffer.mapState === 'unmapped' ) {
  47058. encoder.copyBufferToBuffer( resolveBuffer, 0, resultBuffer, 0, size );
  47059. }
  47060. }
  47061. /**
  47062. * Resolves the time stamp for the given render context and type.
  47063. *
  47064. * @async
  47065. * @param {RenderContext} renderContext - The render context.
  47066. * @param {String} type - The render context.
  47067. * @return {Promise} A Promise that resolves when the time stamp has been computed.
  47068. */
  47069. async resolveTimestampAsync( renderContext, type = 'render' ) {
  47070. if ( ! this.trackTimestamp ) return;
  47071. const renderContextData = this.get( renderContext );
  47072. if ( renderContextData.currentTimestampQueryBuffers === undefined ) return;
  47073. const { resultBuffer } = renderContextData.currentTimestampQueryBuffers;
  47074. if ( resultBuffer.mapState === 'unmapped' ) {
  47075. await resultBuffer.mapAsync( GPUMapMode.READ );
  47076. const times = new BigUint64Array( resultBuffer.getMappedRange() );
  47077. const duration = Number( times[ 1 ] - times[ 0 ] ) / 1000000;
  47078. this.renderer.info.updateTimestamp( type, duration );
  47079. resultBuffer.unmap();
  47080. }
  47081. }
  47082. // node builder
  47083. /**
  47084. * Returns a node builder for the given render object.
  47085. *
  47086. * @param {RenderObject} object - The render object.
  47087. * @param {Renderer} renderer - The renderer.
  47088. * @return {WGSLNodeBuilder} The node builder.
  47089. */
  47090. createNodeBuilder( object, renderer ) {
  47091. return new WGSLNodeBuilder( object, renderer );
  47092. }
  47093. // program
  47094. /**
  47095. * Creates a shader program from the given programmable stage.
  47096. *
  47097. * @param {ProgrammableStage} program - The programmable stage.
  47098. */
  47099. createProgram( program ) {
  47100. const programGPU = this.get( program );
  47101. programGPU.module = {
  47102. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  47103. entryPoint: 'main'
  47104. };
  47105. }
  47106. /**
  47107. * Destroys the shader program of the given programmable stage.
  47108. *
  47109. * @param {ProgrammableStage} program - The programmable stage.
  47110. */
  47111. destroyProgram( program ) {
  47112. this.delete( program );
  47113. }
  47114. // pipelines
  47115. /**
  47116. * Creates a render pipeline for the given render object.
  47117. *
  47118. * @param {RenderObject} renderObject - The render object.
  47119. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  47120. */
  47121. createRenderPipeline( renderObject, promises ) {
  47122. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  47123. }
  47124. /**
  47125. * Creates a compute pipeline for the given compute node.
  47126. *
  47127. * @param {ComputePipeline} computePipeline - The compute pipeline.
  47128. * @param {Array<BindGroup>} bindings - The bindings.
  47129. */
  47130. createComputePipeline( computePipeline, bindings ) {
  47131. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  47132. }
  47133. /**
  47134. * Prepares the state for encoding render bundles.
  47135. *
  47136. * @param {RenderContext} renderContext - The render context.
  47137. */
  47138. beginBundle( renderContext ) {
  47139. const renderContextData = this.get( renderContext );
  47140. renderContextData._currentPass = renderContextData.currentPass;
  47141. renderContextData._currentSets = renderContextData.currentSets;
  47142. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47143. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  47144. }
  47145. /**
  47146. * After processing render bundles this method finalizes related work.
  47147. *
  47148. * @param {RenderContext} renderContext - The render context.
  47149. * @param {RenderBundle} bundle - The render bundle.
  47150. */
  47151. finishBundle( renderContext, bundle ) {
  47152. const renderContextData = this.get( renderContext );
  47153. const bundleEncoder = renderContextData.currentPass;
  47154. const bundleGPU = bundleEncoder.finish();
  47155. this.get( bundle ).bundleGPU = bundleGPU;
  47156. // restore render pass state
  47157. renderContextData.currentSets = renderContextData._currentSets;
  47158. renderContextData.currentPass = renderContextData._currentPass;
  47159. }
  47160. /**
  47161. * Adds a render bundle to the render context data.
  47162. *
  47163. * @param {RenderContext} renderContext - The render context.
  47164. * @param {RenderBundle} bundle - The render bundle to add.
  47165. */
  47166. addBundle( renderContext, bundle ) {
  47167. const renderContextData = this.get( renderContext );
  47168. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  47169. }
  47170. // bindings
  47171. /**
  47172. * Creates bindings from the given bind group definition.
  47173. *
  47174. * @param {BindGroup} bindGroup - The bind group.
  47175. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47176. * @param {Number} cacheIndex - The cache index.
  47177. * @param {Number} version - The version.
  47178. */
  47179. createBindings( bindGroup, bindings, cacheIndex, version ) {
  47180. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47181. }
  47182. /**
  47183. * Updates the given bind group definition.
  47184. *
  47185. * @param {BindGroup} bindGroup - The bind group.
  47186. * @param {Array<BindGroup>} bindings - Array of bind groups.
  47187. * @param {Number} cacheIndex - The cache index.
  47188. * @param {Number} version - The version.
  47189. */
  47190. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  47191. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  47192. }
  47193. /**
  47194. * Updates a buffer binding.
  47195. *
  47196. * @param {Buffer} binding - The buffer binding to update.
  47197. */
  47198. updateBinding( binding ) {
  47199. this.bindingUtils.updateBinding( binding );
  47200. }
  47201. // attributes
  47202. /**
  47203. * Creates the buffer of an indexed shader attribute.
  47204. *
  47205. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  47206. */
  47207. createIndexAttribute( attribute ) {
  47208. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47209. }
  47210. /**
  47211. * Creates the GPU buffer of a shader attribute.
  47212. *
  47213. * @param {BufferAttribute} attribute - The buffer attribute.
  47214. */
  47215. createAttribute( attribute ) {
  47216. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47217. }
  47218. /**
  47219. * Creates the GPU buffer of a storage attribute.
  47220. *
  47221. * @param {BufferAttribute} attribute - The buffer attribute.
  47222. */
  47223. createStorageAttribute( attribute ) {
  47224. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47225. }
  47226. /**
  47227. * Creates the GPU buffer of an indirect storage attribute.
  47228. *
  47229. * @param {BufferAttribute} attribute - The buffer attribute.
  47230. */
  47231. createIndirectStorageAttribute( attribute ) {
  47232. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  47233. }
  47234. /**
  47235. * Updates the GPU buffer of a shader attribute.
  47236. *
  47237. * @param {BufferAttribute} attribute - The buffer attribute to update.
  47238. */
  47239. updateAttribute( attribute ) {
  47240. this.attributeUtils.updateAttribute( attribute );
  47241. }
  47242. /**
  47243. * Destroys the GPU buffer of a shader attribute.
  47244. *
  47245. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  47246. */
  47247. destroyAttribute( attribute ) {
  47248. this.attributeUtils.destroyAttribute( attribute );
  47249. }
  47250. // canvas
  47251. /**
  47252. * Triggers an update of the default render pass descriptor.
  47253. */
  47254. updateSize() {
  47255. this.colorBuffer = this.textureUtils.getColorBuffer();
  47256. this.defaultRenderPassdescriptor = null;
  47257. }
  47258. // utils public
  47259. /**
  47260. * Returns the maximum anisotropy texture filtering value.
  47261. *
  47262. * @return {Number} The maximum anisotropy texture filtering value.
  47263. */
  47264. getMaxAnisotropy() {
  47265. return 16;
  47266. }
  47267. /**
  47268. * Checks if the given feature is supported by the backend.
  47269. *
  47270. * @param {String} name - The feature's name.
  47271. * @return {Boolean} Whether the feature is supported or not.
  47272. */
  47273. hasFeature( name ) {
  47274. return this.device.features.has( name );
  47275. }
  47276. /**
  47277. * Copies data of the given source texture to the given destination texture.
  47278. *
  47279. * @param {Texture} srcTexture - The source texture.
  47280. * @param {Texture} dstTexture - The destination texture.
  47281. * @param {Vector4?} [srcRegion=null] - The region of the source texture to copy.
  47282. * @param {(Vector2|Vector3)?} [dstPosition=null] - The destination position of the copy.
  47283. * @param {Number} [level=0] - The mip level to copy.
  47284. */
  47285. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, level = 0 ) {
  47286. let dstX = 0;
  47287. let dstY = 0;
  47288. let dstLayer = 0;
  47289. let srcX = 0;
  47290. let srcY = 0;
  47291. let srcLayer = 0;
  47292. let srcWidth = srcTexture.image.width;
  47293. let srcHeight = srcTexture.image.height;
  47294. if ( srcRegion !== null ) {
  47295. srcX = srcRegion.x;
  47296. srcY = srcRegion.y;
  47297. srcLayer = srcRegion.z || 0;
  47298. srcWidth = srcRegion.width;
  47299. srcHeight = srcRegion.height;
  47300. }
  47301. if ( dstPosition !== null ) {
  47302. dstX = dstPosition.x;
  47303. dstY = dstPosition.y;
  47304. dstLayer = dstPosition.z || 0;
  47305. }
  47306. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  47307. const sourceGPU = this.get( srcTexture ).texture;
  47308. const destinationGPU = this.get( dstTexture ).texture;
  47309. encoder.copyTextureToTexture(
  47310. {
  47311. texture: sourceGPU,
  47312. mipLevel: level,
  47313. origin: { x: srcX, y: srcY, z: srcLayer }
  47314. },
  47315. {
  47316. texture: destinationGPU,
  47317. mipLevel: level,
  47318. origin: { x: dstX, y: dstY, z: dstLayer }
  47319. },
  47320. [
  47321. srcWidth,
  47322. srcHeight,
  47323. 1
  47324. ]
  47325. );
  47326. this.device.queue.submit( [ encoder.finish() ] );
  47327. }
  47328. /**
  47329. * Copies the current bound framebuffer to the given texture.
  47330. *
  47331. * @param {Texture} texture - The destination texture.
  47332. * @param {RenderContext} renderContext - The render context.
  47333. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  47334. */
  47335. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  47336. const renderContextData = this.get( renderContext );
  47337. let sourceGPU = null;
  47338. if ( renderContext.renderTarget ) {
  47339. if ( texture.isDepthTexture ) {
  47340. sourceGPU = this.get( renderContext.depthTexture ).texture;
  47341. } else {
  47342. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  47343. }
  47344. } else {
  47345. if ( texture.isDepthTexture ) {
  47346. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  47347. } else {
  47348. sourceGPU = this.context.getCurrentTexture();
  47349. }
  47350. }
  47351. const destinationGPU = this.get( texture ).texture;
  47352. if ( sourceGPU.format !== destinationGPU.format ) {
  47353. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  47354. return;
  47355. }
  47356. let encoder;
  47357. if ( renderContextData.currentPass ) {
  47358. renderContextData.currentPass.end();
  47359. encoder = renderContextData.encoder;
  47360. } else {
  47361. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  47362. }
  47363. encoder.copyTextureToTexture(
  47364. {
  47365. texture: sourceGPU,
  47366. origin: [ rectangle.x, rectangle.y, 0 ],
  47367. },
  47368. {
  47369. texture: destinationGPU
  47370. },
  47371. [
  47372. rectangle.z,
  47373. rectangle.w
  47374. ]
  47375. );
  47376. if ( texture.generateMipmaps ) this.textureUtils.generateMipmaps( texture );
  47377. if ( renderContextData.currentPass ) {
  47378. const { descriptor } = renderContextData;
  47379. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  47380. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  47381. }
  47382. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  47383. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  47384. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  47385. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  47386. if ( renderContext.viewport ) {
  47387. this.updateViewport( renderContext );
  47388. }
  47389. if ( renderContext.scissor ) {
  47390. const { x, y, width, height } = renderContext.scissorValue;
  47391. renderContextData.currentPass.setScissorRect( x, y, width, height );
  47392. }
  47393. } else {
  47394. this.device.queue.submit( [ encoder.finish() ] );
  47395. }
  47396. }
  47397. }
  47398. class IESSpotLight extends SpotLight {
  47399. constructor( color, intensity, distance, angle, penumbra, decay ) {
  47400. super( color, intensity, distance, angle, penumbra, decay );
  47401. this.iesMap = null;
  47402. }
  47403. copy( source, recursive ) {
  47404. super.copy( source, recursive );
  47405. this.iesMap = source.iesMap;
  47406. return this;
  47407. }
  47408. }
  47409. /**
  47410. * This version of a node library represents a basic version
  47411. * just focusing on lights and tone mapping techniques.
  47412. *
  47413. * @private
  47414. * @augments NodeLibrary
  47415. */
  47416. class BasicNodeLibrary extends NodeLibrary {
  47417. /**
  47418. * Constructs a new basic node library.
  47419. */
  47420. constructor() {
  47421. super();
  47422. this.addLight( PointLightNode, PointLight );
  47423. this.addLight( DirectionalLightNode, DirectionalLight );
  47424. this.addLight( RectAreaLightNode, RectAreaLight );
  47425. this.addLight( SpotLightNode, SpotLight );
  47426. this.addLight( AmbientLightNode, AmbientLight );
  47427. this.addLight( HemisphereLightNode, HemisphereLight );
  47428. this.addLight( LightProbeNode, LightProbe );
  47429. this.addLight( IESSpotLightNode, IESSpotLight );
  47430. this.addToneMapping( linearToneMapping, LinearToneMapping );
  47431. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  47432. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  47433. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  47434. this.addToneMapping( agxToneMapping, AgXToneMapping );
  47435. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  47436. }
  47437. }
  47438. /**
  47439. * This alternative version of {@link WebGPURenderer} only supports node materials.
  47440. * So classes like `MeshBasicMaterial` are not compatible.
  47441. *
  47442. * @augments module:Renderer~Renderer
  47443. */
  47444. class WebGPURenderer extends Renderer {
  47445. /**
  47446. * Constructs a new WebGPU renderer.
  47447. *
  47448. * @param {Object} parameters - The configuration parameter.
  47449. * @param {Boolean} [parameters.logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  47450. * @param {Boolean} [parameters.alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  47451. * @param {Boolean} [parameters.depth=true] - Whether the default framebuffer should have a depth buffer or not.
  47452. * @param {Boolean} [parameters.stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  47453. * @param {Boolean} [parameters.antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  47454. * @param {Number} [parameters.samples=0] - When `antialias` is `true`, `4` samples are used by default. Set this parameter to any other integer value than 0
  47455. * to overwrite the default.
  47456. * @param {Boolean} [parameters.forceWebGL=false] - If set to `true`, the renderer uses it
  47457. * WebGL 2 backend no matter if WebGPU is supported or not.
  47458. */
  47459. constructor( parameters = {} ) {
  47460. let BackendClass;
  47461. if ( parameters.forceWebGL ) {
  47462. BackendClass = WebGLBackend;
  47463. } else {
  47464. BackendClass = WebGPUBackend;
  47465. parameters.getFallback = () => {
  47466. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  47467. return new WebGLBackend( parameters );
  47468. };
  47469. }
  47470. const backend = new BackendClass( parameters );
  47471. super( backend, parameters );
  47472. /**
  47473. * The generic default value is overwritten with the
  47474. * standard node library for type mapping. Material
  47475. * mapping is not supported with this version.
  47476. *
  47477. * @type {BasicNodeLibrary}
  47478. */
  47479. this.library = new BasicNodeLibrary();
  47480. /**
  47481. * This flag can be used for type testing.
  47482. *
  47483. * @type {Boolean}
  47484. * @readonly
  47485. * @default true
  47486. */
  47487. this.isWebGPURenderer = true;
  47488. }
  47489. }
  47490. /**
  47491. * A specialized group which enables applications access to the
  47492. * Render Bundle API of WebGPU. The group with all its descendant nodes
  47493. * are considered as one render bundle and processed as such by
  47494. * the renderer.
  47495. *
  47496. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  47497. * With a WebGL backend, the group can technically be rendered but without
  47498. * any performance improvements.
  47499. *
  47500. * @augments Group
  47501. */
  47502. class BundleGroup extends Group {
  47503. /**
  47504. * Constructs a new bundle group.
  47505. */
  47506. constructor() {
  47507. super();
  47508. /**
  47509. * This flag can be used for type testing.
  47510. *
  47511. * @type {Boolean}
  47512. * @readonly
  47513. * @default true
  47514. */
  47515. this.isBundleGroup = true;
  47516. /**
  47517. * This property is only relevant for detecting types
  47518. * during serialization/deserialization. It should always
  47519. * match the class name.
  47520. *
  47521. * @type {String}
  47522. * @readonly
  47523. * @default 'BundleGroup'
  47524. */
  47525. this.type = 'BundleGroup';
  47526. /**
  47527. * Whether the bundle is static or not. When set to `true`, the structure
  47528. * is assumed to be static and does not change. E.g. no new objects are
  47529. * added to the group
  47530. *
  47531. * If a change is required, an update can still be forced by setting the
  47532. * `needsUpdate` flag to `true`.
  47533. *
  47534. * @type {Boolean}
  47535. * @default true
  47536. */
  47537. this.static = true;
  47538. /**
  47539. * The bundle group's version.
  47540. *
  47541. * @type {Number}
  47542. * @readonly
  47543. * @default 0
  47544. */
  47545. this.version = 0;
  47546. }
  47547. /**
  47548. * Set this property to `true` when the bundle group has changed.
  47549. *
  47550. * @type {Boolean}
  47551. * @default false
  47552. * @param {Boolean} value
  47553. */
  47554. set needsUpdate( value ) {
  47555. if ( value === true ) this.version ++;
  47556. }
  47557. }
  47558. /**
  47559. * This module is responsible to manage the post processing setups in apps.
  47560. * You usually create a single instance of this class and use it to define
  47561. * the output of your post processing effect chain.
  47562. * ```js
  47563. * const postProcessing = new PostProcessing( renderer );
  47564. *
  47565. * const scenePass = pass( scene, camera );
  47566. *
  47567. * postProcessing.outputNode = scenePass;
  47568. * ```
  47569. */
  47570. class PostProcessing {
  47571. /**
  47572. * Constructs a new post processing management module.
  47573. *
  47574. * @param {Renderer} renderer - A reference to the renderer.
  47575. * @param {Node<vec4>} outputNode - An optional output node.
  47576. */
  47577. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  47578. /**
  47579. * A reference to the renderer.
  47580. *
  47581. * @type {Renderer}
  47582. */
  47583. this.renderer = renderer;
  47584. /**
  47585. * A node which defines the final output of the post
  47586. * processing. This is usually the last node in a chain
  47587. * of effect nodes.
  47588. *
  47589. * @type {Node<vec4>}
  47590. */
  47591. this.outputNode = outputNode;
  47592. /**
  47593. * Whether the default output tone mapping and color
  47594. * space transformation should be enabled or not.
  47595. *
  47596. * It is enabled by default by it must be disabled when
  47597. * effects must be executed after tone mapping and color
  47598. * space conversion. A typical example is FXAA which
  47599. * requires sRGB input.
  47600. *
  47601. * When set to `false`, the app must control the output
  47602. * transformation with `RenderOutputNode`.
  47603. *
  47604. * ```js
  47605. * const outputPass = renderOutput( scenePass );
  47606. * ```
  47607. *
  47608. * @type {Boolean}
  47609. */
  47610. this.outputColorTransform = true;
  47611. /**
  47612. * Must be set to `true` when the output node changes.
  47613. *
  47614. * @type {Node<vec4>}
  47615. */
  47616. this.needsUpdate = true;
  47617. const material = new NodeMaterial();
  47618. material.name = 'PostProcessing';
  47619. /**
  47620. * The full screen quad that is used to render
  47621. * the effects.
  47622. *
  47623. * @private
  47624. * @type {QuadMesh}
  47625. */
  47626. this._quadMesh = new QuadMesh( material );
  47627. }
  47628. /**
  47629. * When `PostProcessing` is used to apply post processing effects,
  47630. * the application must use this version of `render()` inside
  47631. * its animation loop (not the one from the renderer).
  47632. */
  47633. render() {
  47634. this._update();
  47635. const renderer = this.renderer;
  47636. const toneMapping = renderer.toneMapping;
  47637. const outputColorSpace = renderer.outputColorSpace;
  47638. renderer.toneMapping = NoToneMapping;
  47639. renderer.outputColorSpace = LinearSRGBColorSpace;
  47640. //
  47641. this._quadMesh.render( renderer );
  47642. //
  47643. renderer.toneMapping = toneMapping;
  47644. renderer.outputColorSpace = outputColorSpace;
  47645. }
  47646. /**
  47647. * Frees internal resources.
  47648. */
  47649. dispose() {
  47650. this._quadMesh.material.dispose();
  47651. }
  47652. /**
  47653. * Updates the state of the module.
  47654. *
  47655. * @private
  47656. */
  47657. _update() {
  47658. if ( this.needsUpdate === true ) {
  47659. const renderer = this.renderer;
  47660. const toneMapping = renderer.toneMapping;
  47661. const outputColorSpace = renderer.outputColorSpace;
  47662. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  47663. this._quadMesh.material.needsUpdate = true;
  47664. this.needsUpdate = false;
  47665. }
  47666. }
  47667. /**
  47668. * When `PostProcessing` is used to apply post processing effects,
  47669. * the application must use this version of `renderAsync()` inside
  47670. * its animation loop (not the one from the renderer).
  47671. *
  47672. * @async
  47673. * @return {Promise} A Promise that resolves when the render has been finished.
  47674. */
  47675. async renderAsync() {
  47676. this._update();
  47677. const renderer = this.renderer;
  47678. const toneMapping = renderer.toneMapping;
  47679. const outputColorSpace = renderer.outputColorSpace;
  47680. renderer.toneMapping = NoToneMapping;
  47681. renderer.outputColorSpace = LinearSRGBColorSpace;
  47682. //
  47683. await this._quadMesh.renderAsync( renderer );
  47684. //
  47685. renderer.toneMapping = toneMapping;
  47686. renderer.outputColorSpace = outputColorSpace;
  47687. }
  47688. }
  47689. /**
  47690. * This special type of texture is intended for compute shaders.
  47691. * It can be used to compute the data of a texture with a compute shader.
  47692. *
  47693. * Note: This type of texture can only be used with `WebGPURenderer`
  47694. * and a WebGPU backend.
  47695. *
  47696. * @augments Texture
  47697. */
  47698. class StorageTexture extends Texture {
  47699. /**
  47700. * Constructs a new storage texture.
  47701. *
  47702. * @param {Number} [width=1] - The storage texture's width.
  47703. * @param {Number} [height=1] - The storage texture's height.
  47704. */
  47705. constructor( width = 1, height = 1 ) {
  47706. super();
  47707. /**
  47708. * The image object which just represents the texture's dimension.
  47709. *
  47710. * @type {{width: Number, height: Number}}
  47711. */
  47712. this.image = { width, height };
  47713. /**
  47714. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  47715. *
  47716. * @type {Number}
  47717. */
  47718. this.magFilter = LinearFilter;
  47719. /**
  47720. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  47721. *
  47722. * @type {Number}
  47723. */
  47724. this.minFilter = LinearFilter;
  47725. /**
  47726. * This flag can be used for type testing.
  47727. *
  47728. * @type {Boolean}
  47729. * @readonly
  47730. * @default true
  47731. */
  47732. this.isStorageTexture = true;
  47733. }
  47734. }
  47735. /**
  47736. * This special type of buffer attribute is intended for compute shaders.
  47737. * It can be used to encode draw parameters for indirect draw calls.
  47738. *
  47739. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  47740. * and a WebGPU backend.
  47741. *
  47742. * @augments StorageBufferAttribute
  47743. */
  47744. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  47745. /**
  47746. * Constructs a new storage buffer attribute.
  47747. *
  47748. * @param {Number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  47749. * The subsequent parameter is then obsolete.
  47750. * @param {Number} itemSize - The item size.
  47751. */
  47752. constructor( count, itemSize ) {
  47753. super( count, itemSize, Uint32Array );
  47754. /**
  47755. * This flag can be used for type testing.
  47756. *
  47757. * @type {Boolean}
  47758. * @readonly
  47759. * @default true
  47760. */
  47761. this.isIndirectStorageBufferAttribute = true;
  47762. }
  47763. }
  47764. /**
  47765. * A loader for loading node objects in the three.js JSON Object/Scene format.
  47766. *
  47767. * @augments Loader
  47768. */
  47769. class NodeLoader extends Loader {
  47770. /**
  47771. * Constructs a new node loader.
  47772. *
  47773. * @param {LoadingManager?} manager - A reference to a loading manager.
  47774. */
  47775. constructor( manager ) {
  47776. super( manager );
  47777. /**
  47778. * Represents a dictionary of textures.
  47779. *
  47780. * @type {Object<String,Texture>}
  47781. */
  47782. this.textures = {};
  47783. /**
  47784. * Represents a dictionary of node types.
  47785. *
  47786. * @type {Object<String,Node.constructor>}
  47787. */
  47788. this.nodes = {};
  47789. }
  47790. /**
  47791. * Loads the node definitions from the given URL.
  47792. *
  47793. * @param {String} url - The path/URL of the file to be loaded.
  47794. * @param {Function} onLoad - Will be called when load completes.
  47795. * @param {Function} onProgress - Will be called while load progresses.
  47796. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  47797. */
  47798. load( url, onLoad, onProgress, onError ) {
  47799. const loader = new FileLoader( this.manager );
  47800. loader.setPath( this.path );
  47801. loader.setRequestHeader( this.requestHeader );
  47802. loader.setWithCredentials( this.withCredentials );
  47803. loader.load( url, ( text ) => {
  47804. try {
  47805. onLoad( this.parse( JSON.parse( text ) ) );
  47806. } catch ( e ) {
  47807. if ( onError ) {
  47808. onError( e );
  47809. } else {
  47810. console.error( e );
  47811. }
  47812. this.manager.itemError( url );
  47813. }
  47814. }, onProgress, onError );
  47815. }
  47816. /**
  47817. * Parse the node dependencies for the loaded node.
  47818. *
  47819. * @param {Object} json - The JSON definition
  47820. * @return {Object<String,Node>} A dictionary with node dependencies.
  47821. */
  47822. parseNodes( json ) {
  47823. const nodes = {};
  47824. if ( json !== undefined ) {
  47825. for ( const nodeJSON of json ) {
  47826. const { uuid, type } = nodeJSON;
  47827. nodes[ uuid ] = this.createNodeFromType( type );
  47828. nodes[ uuid ].uuid = uuid;
  47829. }
  47830. const meta = { nodes, textures: this.textures };
  47831. for ( const nodeJSON of json ) {
  47832. nodeJSON.meta = meta;
  47833. const node = nodes[ nodeJSON.uuid ];
  47834. node.deserialize( nodeJSON );
  47835. delete nodeJSON.meta;
  47836. }
  47837. }
  47838. return nodes;
  47839. }
  47840. /**
  47841. * Parses the node from the given JSON.
  47842. *
  47843. * @param {Object} json - The JSON definition
  47844. * @return {Node} The parsed node.
  47845. */
  47846. parse( json ) {
  47847. const node = this.createNodeFromType( json.type );
  47848. node.uuid = json.uuid;
  47849. const nodes = this.parseNodes( json.nodes );
  47850. const meta = { nodes, textures: this.textures };
  47851. json.meta = meta;
  47852. node.deserialize( json );
  47853. delete json.meta;
  47854. return node;
  47855. }
  47856. /**
  47857. * Defines the dictionary of textures.
  47858. *
  47859. * @param {Object<String,Texture>} value - The texture library defines as `<uuid,texture>`.
  47860. * @return {NodeLoader} A reference to this loader.
  47861. */
  47862. setTextures( value ) {
  47863. this.textures = value;
  47864. return this;
  47865. }
  47866. /**
  47867. * Defines the dictionary of node types.
  47868. *
  47869. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  47870. * @return {NodeLoader} A reference to this loader.
  47871. */
  47872. setNodes( value ) {
  47873. this.nodes = value;
  47874. return this;
  47875. }
  47876. /**
  47877. * Creates a node object from the given type.
  47878. *
  47879. * @param {String} type - The node type.
  47880. * @return {Node} The created node instance.
  47881. */
  47882. createNodeFromType( type ) {
  47883. if ( this.nodes[ type ] === undefined ) {
  47884. console.error( 'THREE.NodeLoader: Node type not found:', type );
  47885. return float();
  47886. }
  47887. return nodeObject( new this.nodes[ type ]() );
  47888. }
  47889. }
  47890. /**
  47891. * A special type of material loader for loading node materials.
  47892. *
  47893. * @augments MaterialLoader
  47894. */
  47895. class NodeMaterialLoader extends MaterialLoader {
  47896. /**
  47897. * Constructs a new node material loader.
  47898. *
  47899. * @param {LoadingManager?} manager - A reference to a loading manager.
  47900. */
  47901. constructor( manager ) {
  47902. super( manager );
  47903. /**
  47904. * Represents a dictionary of node types.
  47905. *
  47906. * @type {Object<String,Node.constructor>}
  47907. */
  47908. this.nodes = {};
  47909. /**
  47910. * Represents a dictionary of node material types.
  47911. *
  47912. * @type {Object<String,NodeMaterial.constructor>}
  47913. */
  47914. this.nodeMaterials = {};
  47915. }
  47916. /**
  47917. * Parses the node material from the given JSON.
  47918. *
  47919. * @param {Object} json - The JSON definition
  47920. * @return {NodeMaterial}. The parsed material.
  47921. */
  47922. parse( json ) {
  47923. const material = super.parse( json );
  47924. const nodes = this.nodes;
  47925. const inputNodes = json.inputNodes;
  47926. for ( const property in inputNodes ) {
  47927. const uuid = inputNodes[ property ];
  47928. material[ property ] = nodes[ uuid ];
  47929. }
  47930. return material;
  47931. }
  47932. /**
  47933. * Defines the dictionary of node types.
  47934. *
  47935. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  47936. * @return {NodeLoader} A reference to this loader.
  47937. */
  47938. setNodes( value ) {
  47939. this.nodes = value;
  47940. return this;
  47941. }
  47942. /**
  47943. * Defines the dictionary of node material types.
  47944. *
  47945. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  47946. * @return {NodeLoader} A reference to this loader.
  47947. */
  47948. setNodeMaterials( value ) {
  47949. this.nodeMaterials = value;
  47950. return this;
  47951. }
  47952. /**
  47953. * Creates a node material from the given type.
  47954. *
  47955. * @param {String} type - The node material type.
  47956. * @return {Node} The created node material instance.
  47957. */
  47958. createMaterialFromType( type ) {
  47959. const materialClass = this.nodeMaterials[ type ];
  47960. if ( materialClass !== undefined ) {
  47961. return new materialClass();
  47962. }
  47963. return super.createMaterialFromType( type );
  47964. }
  47965. }
  47966. /**
  47967. * A special type of object loader for loading 3D objects using
  47968. * node materials.
  47969. *
  47970. * @augments ObjectLoader
  47971. */
  47972. class NodeObjectLoader extends ObjectLoader {
  47973. /**
  47974. * Constructs a new node object loader.
  47975. *
  47976. * @param {LoadingManager?} manager - A reference to a loading manager.
  47977. */
  47978. constructor( manager ) {
  47979. super( manager );
  47980. /**
  47981. * Represents a dictionary of node types.
  47982. *
  47983. * @type {Object<String,Node.constructor>}
  47984. */
  47985. this.nodes = {};
  47986. /**
  47987. * Represents a dictionary of node material types.
  47988. *
  47989. * @type {Object<String,NodeMaterial.constructor>}
  47990. */
  47991. this.nodeMaterials = {};
  47992. /**
  47993. * A reference to hold the `nodes` JSON property.
  47994. *
  47995. * @private
  47996. * @type {Object?}
  47997. */
  47998. this._nodesJSON = null;
  47999. }
  48000. /**
  48001. * Defines the dictionary of node types.
  48002. *
  48003. * @param {Object<String,Node.constructor>} value - The node library defined as `<classname,class>`.
  48004. * @return {NodeLoader} A reference to this loader.
  48005. */
  48006. setNodes( value ) {
  48007. this.nodes = value;
  48008. return this;
  48009. }
  48010. /**
  48011. * Defines the dictionary of node material types.
  48012. *
  48013. * @param {Object<String,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  48014. * @return {NodeLoader} A reference to this loader.
  48015. */
  48016. setNodeMaterials( value ) {
  48017. this.nodeMaterials = value;
  48018. return this;
  48019. }
  48020. /**
  48021. * Parses the node objects from the given JSON.
  48022. *
  48023. * @param {Object} json - The JSON definition
  48024. * @param {Function} onLoad - The onLoad callback function.
  48025. * @return {Object3D}. The parsed 3D object.
  48026. */
  48027. parse( json, onLoad ) {
  48028. this._nodesJSON = json.nodes;
  48029. const data = super.parse( json, onLoad );
  48030. this._nodesJSON = null; // dispose
  48031. return data;
  48032. }
  48033. /**
  48034. * Parses the node objects from the given JSON and textures.
  48035. *
  48036. * @param {Object} json - The JSON definition
  48037. * @param {Object<String,Texture>} textures - The texture library.
  48038. * @return {Object<String,Node>}. The parsed nodes.
  48039. */
  48040. parseNodes( json, textures ) {
  48041. if ( json !== undefined ) {
  48042. const loader = new NodeLoader();
  48043. loader.setNodes( this.nodes );
  48044. loader.setTextures( textures );
  48045. return loader.parseNodes( json );
  48046. }
  48047. return {};
  48048. }
  48049. /**
  48050. * Parses the node objects from the given JSON and textures.
  48051. *
  48052. * @param {Object} json - The JSON definition
  48053. * @param {Object<String,Texture>} textures - The texture library.
  48054. * @return {Object<String,NodeMaterial>}. The parsed materials.
  48055. */
  48056. parseMaterials( json, textures ) {
  48057. const materials = {};
  48058. if ( json !== undefined ) {
  48059. const nodes = this.parseNodes( this._nodesJSON, textures );
  48060. const loader = new NodeMaterialLoader();
  48061. loader.setTextures( textures );
  48062. loader.setNodes( nodes );
  48063. loader.setNodeMaterials( this.nodeMaterials );
  48064. for ( let i = 0, l = json.length; i < l; i ++ ) {
  48065. const data = json[ i ];
  48066. materials[ data.uuid ] = loader.parse( data );
  48067. }
  48068. }
  48069. return materials;
  48070. }
  48071. }
  48072. /**
  48073. * In earlier three.js versions, clipping was defined globally
  48074. * on the renderer or on material level. This special version of
  48075. * `THREE.Group` allows to encode the clipping state into the scene
  48076. * graph. Meaning if you create an instance of this group, all
  48077. * descendant 3D objects will be affected by the respective clipping
  48078. * planes.
  48079. *
  48080. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  48081. *
  48082. * @augments Group
  48083. */
  48084. class ClippingGroup extends Group {
  48085. /**
  48086. * Constructs a new clipping group.
  48087. */
  48088. constructor() {
  48089. super();
  48090. /**
  48091. * This flag can be used for type testing.
  48092. *
  48093. * @type {Boolean}
  48094. * @readonly
  48095. * @default true
  48096. */
  48097. this.isClippingGroup = true;
  48098. /**
  48099. * An array with clipping planes.
  48100. *
  48101. * @type {Array<Plane>}
  48102. */
  48103. this.clippingPlanes = [];
  48104. /**
  48105. * Whether clipping should be enabled or not.
  48106. *
  48107. * @type {Boolean}
  48108. * @default true
  48109. */
  48110. this.enabled = true;
  48111. /**
  48112. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  48113. *
  48114. * @type {Boolean}
  48115. * @default false
  48116. */
  48117. this.clipIntersection = false;
  48118. /**
  48119. * Whether shadows should be clipped or not.
  48120. *
  48121. * @type {Boolean}
  48122. * @default false
  48123. */
  48124. this.clipShadows = false;
  48125. }
  48126. }
  48127. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, DataArrayTexture, DataTexture, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, ExpressionNode, FileLoader, Float16BufferAttribute, Float32BufferAttribute, FloatType, FramebufferTexture, FrontFacingNode, FrontSide, Frustum, FunctionCallNode, FunctionNode, FunctionOverloadingNode, GLSLNodeParser, GreaterCompare, GreaterDepth, GreaterEqualCompare, GreaterEqualDepth, GreaterEqualStencilFunc, GreaterStencilFunc, Group, HalfFloatType, HemisphereLight, HemisphereLightNode, IESSpotLight, IESSpotLightNode, IncrementStencilOp, IncrementWrapStencilOp, IndexNode, IndirectStorageBufferAttribute, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, Loader, LoopNode, LuminanceAlphaFormat, LuminanceFormat, MRTNode, MatcapUVNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, PropertyNode, QuadMesh, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号